package cn.e4j.modular.erp.service.impl;

import cn.e4j.core.dto.Dtos;
import cn.e4j.core.dto.impl.Dto;
import cn.e4j.core.shiro.ShiroKit;
import cn.e4j.core.shiro.ShiroUser;
import cn.e4j.core.util.DateUtils;
import cn.e4j.core.util.LangUtils;
import cn.e4j.core.util.StringUtils;
import cn.e4j.modular.crm.entity.*;
import cn.e4j.modular.crm.service.impl.*;
import cn.e4j.modular.erp.mapper.T100Mapper;
import cn.e4j.modular.erp.service.Erp;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.*;

/**
 * T100逻辑处理
 * Created by ganjia on 2019-09-18.
 */
@Service
public class T100ServiceImpl extends ServiceImpl<T100Mapper, GwamT> implements Erp {

    @Autowired
    MmrwTServiceImpl mmrwTService;

    @Autowired
    GwcsTServiceImpl gwcsTService;

    @Autowired
    GwakTServiceImpl gwakTService;

    @Autowired
    MmrxTServiceImpl mmrxTService;

    @Autowired
    GwdfTServiceImpl gwdfTService;

    @Transactional(readOnly = true)
    public List<Dto> getSiteList(Page<Object> page, Dto dto) {
        return this.baseMapper.getSiteList(page, dto);
    }

    // 获取营运中心名称
    public Dto getAzpFile(Dto inDto) {
        String ERP_Link = inDto.getString("ERP_Link");
        String bizcode = inDto.getString("BIZ_CODE");

        String query = String.format("SELECT OOEFL001, OOEFL003 FROM OOEFL_T WHERE OOEFL001 = ''%s'' ",bizcode);
        String sql = String.format("SELECT * FROM OPENQUERY(%s,'%s')",ERP_Link,query);
        inDto.put("sql",sql);
        Dto outDto = this.baseMapper.selectExecSql(inDto);
        if(outDto != null) {
            outDto.put("AZP01",outDto.getString("OOEFL001"));
            outDto.put("AZP02",outDto.getString("OOEFL003"));
        }
        return outDto;
    }

    /**
     * 维修费用结算转订单(gwei024)
     */
    public JSONArray transfer024(Dto inDto) {
        ShiroUser shiroUser = ShiroKit.getUser();
        String[] selectionIds = inDto.getString("datas").split(",");
        List list = Arrays.asList(selectionIds);
        JSONArray json = new JSONArray();
        Set set = new HashSet(list);
        String[] rid = (String[]) set.toArray(new String[0]);

        for (String data : rid) {
            inDto.put("MMRWDOCNO", data);

            //根据单号查询维修费用结算表数据
            List<Dto> mmrwData = this.mmrwTService.getMmrwAllData(inDto);

            //查询erp数据库
            Dto dbinfo1 = Dtos.newDto();
            dbinfo1.put("OOEF001", mmrwData.get(0).getString("MMRWPLANT"));
            dbinfo1.put("ERP_Link",inDto.getString("ERP_Link"));
            dbinfo1.put("OOEFENT", inDto.getString("ENT"));
            dbinfo1.put("sqlName", "getOoef");
            String getOoef = this.gwei024Sql(dbinfo1);
            dbinfo1.put("sql",getOoef);
            Dto dbinfo2 = this.baseMapper.selectSql(dbinfo1);

            if (dbinfo2 == null) { //没查到目标数据库  添加失败
                JSONObject jo = new JSONObject();
                jo.put("ERPRESULT", "N");//同步结果  Y  N
                jo.put("MMRWDOCNO", mmrwData.get(0).getString("MMRWDOCNO"));//维修费用结算单号
                jo.put("ERPDOCNO", "");//erp单号
                jo.put("REASON", "目标数据库为空,添加失败");//失败原因
                json.add(jo);
                continue;
            }

            //按法人组织抓取单号
            String docno = DateUtils.getDate("yyyyMMdd") + "001";
            Dto dhinfo = this.mmrwTService.getGwaz(mmrwData.get(0).getString("MMRWLEGAL"));
            inDto.put("INBA", dhinfo.getString("GWAZ002")+'-'+DateUtils.getDate("yyyyMMdd"));
            inDto.put("sqlName","getMaxInbadocno");
            inDto.put("INBAENT",inDto.getString("ENT"));
            inDto.put("INBASITE",mmrwData.get(0).getString("MMRWLEGAL"));
            String getMaxInbadocno = this.gwei024Sql(inDto);
            inDto.put("sql",getMaxInbadocno);
            Dto maxInbadocno = this.baseMapper.selectSql(inDto);
            if(maxInbadocno != null){
                docno = inDto.getString("INBADOCNO");
            }
            docno = dhinfo.getString("GWAZ002") + '-' + docno;

            try {
                int count = 1;
                for (Dto mmrw : mmrwData) {
                    //单身信息
                    Dto qDto = Dtos.newDto();
                    qDto.put("ERP_Link", inDto.getString("ERP_Link"));

                    qDto.put("INBBENT", inDto.getString("ENT"));//企业编号
                    qDto.put("INBBSITE", mmrw.getString("MMRWPLANT"));//营运据点
                    qDto.put("INBBDOCNO", docno); //单据编号
                    qDto.put("INBBSEQ", BigDecimal.valueOf(count)); //项次
                    qDto.put("INBB001", mmrw.getString("MMRW001")); //料件编号
                    qDto.put("INBB002", ""); //产品特征
                    qDto.put("INBB003", ""); //库存管理特征
                    qDto.put("INBB004", ""); //包装容器编号
                    qDto.put("INBB007", ""); //库位
                    qDto.put("INBB008", ""); //限定储位
                    qDto.put("INBB009", ""); //限定批号
                    qDto.put("INBB011", ""); //申请数量
                    qDto.put("INBB012", ""); //实际异动数量
                    qDto.put("INBB013", mmrw.getString("MMRW002")); //参考单位
                    qDto.put("INBB014", mmrw.getBigDecimal("MMRW003")); //参考单位申请数量
                    qDto.put("INBB015", mmrw.getBigDecimal("MMRW003")); //参考单位实际数量
                    qDto.put("INBB016", ""); //理由码
                    qDto.put("INBB017", data); //来源单号
                    qDto.put("INBB018", "N"); //检验否
                    qDto.put("INBB019", ""); //检验合格量
                    qDto.put("INBB020", mmrw.getString("MMRW015")); //单据备注
                    qDto.put("INBB021", ""); //存货备注
                    qDto.put("INBB022", ""); //有效日期
                    qDto.put("INBB200", ""); //商品条码
                    qDto.put("INBB201", ""); //包装单位
                    qDto.put("INBB202", ""); //申请包装数量
                    qDto.put("INBB203", ""); //实际包装数量
                    qDto.put("INBBUNIT", ""); //应用组织
                    qDto.put("INBBDATE", ""); //制造日期

                    qDto.put("sqlName","insert");
                    qDto.put("tableName","INBB_T");
                    String sql = this.gwei024Sql(qDto);
                    qDto.put("sql",sql);
                    this.baseMapper.insertExecSql(qDto);

                    MmrwT mmrwT = new MmrwT();
                    mmrwT.setMMRWACTI("Z");
                    mmrwT.setMMRW013(docno);
                    mmrwT.setMMRW014(String.valueOf(count));
                    UpdateWrapper mmrwTUpdateWrapper = new UpdateWrapper();
                    mmrwTUpdateWrapper.eq("MMRWSEQ",mmrw.getBigDecimal("MMRWSEQ"));
                    mmrwTUpdateWrapper.eq("MMRWSENT",shiroUser.getDBC());
                    mmrwTUpdateWrapper.eq("MMRWDOCNO",data);
                    mmrwT.update(mmrwTUpdateWrapper);
                    count++;
                }

            } catch (Exception e) {
                JSONObject jo = new JSONObject();
                jo.put("ERPRESULT", "N");//同步结果  Y  N
                jo.put("MMRWDOCNO", mmrwData.get(0).getString("MMRWDOCNO"));//维修费用结算单号
                jo.put("ERPDOCNO", "");//erp单号
                jo.put("REASON", "添加INBB表失败");//失败原因

                e.printStackTrace();

                Dto deltb = Dtos.newDto();
                deltb.put("INBBENT", inDto.getString("ENT"));//企业编号
                deltb.put("INBBSITE", mmrwData.get(0).getString("MMRWPLANT"));//营运据点
                deltb.put("INBBDOCNO", docno); //单据编号
                deltb.put("ERP_Link", inDto.getString("ERP_Link"));
                deltb.put("sqlName","delete_inbb_t");
                String sql = this.gwei024Sql(deltb);
                deltb.put("sql",sql);
                this.baseMapper.deleteExecSql(deltb);

                MmrwT mmrwT = new MmrwT();
                mmrwT.setMMRWACTI("Y");
                mmrwT.setMMRW013("");
                mmrwT.setMMRW014("");
                UpdateWrapper mmrwTUpdateWrapper = new UpdateWrapper();
                mmrwTUpdateWrapper.eq("MMRWSENT",shiroUser.getDBC());
                mmrwTUpdateWrapper.eq("MMRWDOCNO",data);
                mmrwT.update(mmrwTUpdateWrapper);

                json.add(jo);
                continue;
            }

            try {
                //单头  订单信息
                Dto mmrwDto = mmrwData.get(0);
                Dto pDto = Dtos.newDto();

                pDto.put("ERP_Link", inDto.getString("ERP_Link"));
                pDto.put("INBAENT", inDto.getString("ENT"));//企业编号
                pDto.put("INBASITE", mmrwDto.getString("MMRWPLANT"));//营运据点
                pDto.put("INBADOCNO", docno); //单据编号
                pDto.put("INBADOCDT", DateUtils.getDate("yyyy-MM-dd")); //输入日期
                pDto.put("INBA001", "1"); //单据类别
                pDto.put("INBA002", DateUtils.getDate("yyyy-MM-dd")); //扣账日期
                pDto.put("INBA003", shiroUser.getACCOUNT()); //申请人员
                pDto.put("INBA004", ""); //申请部门
                pDto.put("INBA005", ""); //来源数据类型
                pDto.put("INBA006", data); //来源单号
                pDto.put("INBA007", ""); //理由码
                pDto.put("INBA008", mmrwDto.getString("MMRW015")); //备注
                pDto.put("INBA009", ""); //保税异动原因
                pDto.put("INBA010", ""); //保税进口报单
                pDto.put("INBA011", ""); //保税进口报单日期
                pDto.put("INBAOWNID", shiroUser.getACCOUNT()); //资料所有者
                pDto.put("INBAOWNDP", ""); //资料所有部门
                pDto.put("INBACRTID", shiroUser.getACCOUNT()); //资料建立者
                pDto.put("INBACRTDP", ""); //资料建立部门
                pDto.put("INBACRTDT", DateUtils.getDate("yyyy-MM-dd")); //资料创建日
                pDto.put("INBAMODID", ""); //资料修改者
                pDto.put("INBAMODDT", ""); //最近修改日
                pDto.put("INBACNFID", ""); //资料确认者
                pDto.put("INBACNFDT", ""); //数据确认日
                pDto.put("INBAPSTID", ""); //资料过账者
                pDto.put("INBAPSTDT", ""); //资料过账日
                pDto.put("INBASTUS", "N"); //状态码
                pDto.put("INBAUNIT", ""); //应用组织

                pDto.put("sqlName","insert");
                pDto.put("tableName","INBA_T");
                String sql = this.gwei024Sql(pDto);
                pDto.put("sql",sql);
                int row = this.baseMapper.insertExecSql(pDto);

                String result = "N";
                if (row > 0) {
                    result = "Y";
                }

                JSONObject jo = new JSONObject();
                jo.put("ERPRESULT", result);//同步结果  Y  N
                jo.put("MMRWDOCNO", mmrwData.get(0).getString("MMRWDOCNO"));//维修费用结算单号
                jo.put("ERPDOCNO", docno);//erp单号
                jo.put("REASON", "");//失败原因
                json.add(jo);
            } catch (Exception e) {
                JSONObject jo = new JSONObject();
                jo.put("ERPRESULT", "N");//同步结果  Y  N
                jo.put("MMRWDOCNO", mmrwData.get(0).getString("MMRWDOCNO"));//维修费用结算单号
                jo.put("ERPDOCNO", docno);//erp单号
                jo.put("REASON", "添加INVTA表失败");//失败原因
                json.add(jo);

                e.printStackTrace();

                Dto deltb = Dtos.newDto();
                deltb.put("INBBENT", inDto.getString("ENT"));//企业编号
                deltb.put("INBBSITE", mmrwData.get(0).getString("MMRWPLANT"));//营运据点
                deltb.put("INBBDOCNO", docno); //单据编号
                deltb.put("ERP_Link", inDto.getString("ERP_Link"));
                deltb.put("sqlName","delete_inbb_t");
                String sql = this.gwei024Sql(deltb);
                deltb.put("sql",sql);
                this.baseMapper.deleteExecSql(deltb);

                MmrwT mmrwT = new MmrwT();
                mmrwT.setMMRWACTI("Y");
                mmrwT.setMMRW013("");
                mmrwT.setMMRW014("");
                UpdateWrapper mmrwTUpdateWrapper = new UpdateWrapper();
                mmrwTUpdateWrapper.eq("MMRWSENT",shiroUser.getDBC());
                mmrwTUpdateWrapper.eq("MMRWDOCNO",data);
                mmrwT.update(mmrwTUpdateWrapper);

                //插入COPTA 失败  整张订单跳过 进行下个订单
                e.printStackTrace();
                continue;
            }
        }
        return json;
    }

    public Dto restore024(Dto inDto) {
        Dto outDto = Dtos.newDto();
        ShiroUser shiroUser = ShiroKit.getUser();
        String[] selectionIds = inDto.getString("datas").split(",");
        List list = Arrays.asList(selectionIds);
        Set set = new HashSet(list);
        String[] rid = (String[]) set.toArray(new String[0]);
        int rows = 0;
        for (String data : rid) {
            inDto.put("MMRWDOCNO", data);

            //根据单号查询维修费用结算表数据
            List<Dto> mmrwData = this.mmrwTService.getMmrwAllData(inDto);

            inDto.put("ERP_Link", inDto.getString("ERP_Link"));
            inDto.put("INBAENT", inDto.getString("ENT"));//企业编号
            inDto.put("INBASITE", mmrwData.get(0).getString("MMRWPLANT"));//营运据点
            inDto.put("INBADOCNO", mmrwData.get(0).getString("MMRW013"));
            inDto.put("sqlName","getINBA");
            String getINBA = this.gwei024Sql(inDto);
            inDto.put("sql", getINBA);
            Dto INBAinfo = this.baseMapper.selectSql(inDto);
            if (INBAinfo == null) {
                MmrwT mmrwT = new MmrwT();
                mmrwT.setMMRWACTI("Y");
                mmrwT.setMMRW013("");
                mmrwT.setMMRW014("");
                UpdateWrapper mmrwTUpdateWrapper = new UpdateWrapper();
                mmrwTUpdateWrapper.eq("MMRWSENT",shiroUser.getDBC());
                mmrwTUpdateWrapper.eq("MMRWDOCNO",data);
                mmrwT.update(mmrwTUpdateWrapper);
                outDto.put("docno", "找不到对应ERP订单");
            } else if (INBAinfo.getString("INBASTUS").equals("N")) {
                Dto inDto2 = Dtos.newDto();
                inDto2.put("ERP_Link", inDto.getString("ERP_Link"));
                inDto2.put("INBAENT", inDto.getString("ENT"));
                inDto2.put("INBASITE", mmrwData.get(0).getString("MMRWPLANT"));//营运据点
                inDto2.put("INBADOCNO", mmrwData.get(0).getString("MMRW013"));
                inDto2.put("INBASTUS", "X");
                inDto2.put("sqlName","updateINBA");
                String updateINBA = this.gwei024Sql(inDto2);
                inDto2.put("sql", updateINBA);
                this.baseMapper.updateExecSql(inDto2);

                MmrwT mmrwT = new MmrwT();
                mmrwT.setMMRWACTI("Y");
                mmrwT.setMMRW013("");
                mmrwT.setMMRW014("");
                UpdateWrapper mmrwTUpdateWrapper = new UpdateWrapper();
                mmrwTUpdateWrapper.eq("MMRWSENT",shiroUser.getDBC());
                mmrwTUpdateWrapper.eq("MMRWDOCNO",data);
                mmrwT.update(mmrwTUpdateWrapper);
                outDto.put("docno", "操作成功");
            } else if (INBAinfo.getString("INBASTUS").equals("Y")) {
                outDto.put("docno", "ERP单据已经审核不能还原");
            }
            rows++;
        }
        return outDto;
    }

    public String gwei024Sql(Dto inDto){
        String sql = "";
        if("delete_inbb_t".equals(inDto.getString("sqlName"))){
            String query = "SELECT * FROM INBB_T WHERE INBBENT=" + inDto.getBigDecimal("INBBENT") + " AND INBBSITE=''" + inDto.getString("INBBSITE") +"'' AND INBBDOCNO=''" + inDto.getString("INBBDOCNO") +"''";
            sql = "DELETE openquery(" + inDto.getString("ERP_Link")+",'"+ query + "')";
        }else if("getINBA".equals(inDto.getString("sqlName"))){
            String query = "SELECT INBADOCNO, INBASTUS FROM INBA_T WHERE INBAENT="+ inDto.getBigDecimal("INBAENT") + " AND INBASITE=''" + inDto.getString("INBASITE") +"'' AND INBADOCNO=''" + inDto.getString("INBADOCNO") +"''";
            sql = "SELECT * FROM openquery(" + inDto.getString("ERP_Link")+",'" + query + "')";
        }else if("updateINBA".equals(inDto.getString("sqlName"))){
            String query = "SELECT * FROM INBA_T WHERE INBAENT="+ inDto.getBigDecimal("INBAENT") + " AND INBASITE=''" + inDto.getString("INBASITE") +"'' AND INBADOCNO=''" + inDto.getString("INBADOCNO") +"''";
            sql = "UPDATE openquery(" + inDto.getString("ERP_Link")+",'" + query + "') SET INBASTUS='" + inDto.getString("INBASTUS")+"'";
        }else if("insert".equals(inDto.getString("sqlName"))){
            sql = this.generateInsertSql(inDto, inDto.getString("tableName"));
        }else if("getMaxInbadocno".equals(inDto.getString("sqlName"))){
            String query = "SELECT MAX(SUBSTR(INBADOCNO,INSTR(INBADOCNO,''-'',-1)+1)) AS INBADOCNO FROM INBA_T WHERE INBAENT=" + inDto.getBigDecimal("INBAENT") + " AND INBASITE=''" + inDto.getString("INBASITE")
                    +"'' AND INBADOCNO LIKE ''%"+ inDto.getString("INBA")+"%''";
            sql = "SELECT CAST(CAST(INBADOCNO AS bigint)+1 AS CHAR(11)) AS INBADOCNO FROM OPENQUERY(" + inDto.getString("ERP_Link")+",'"+query+"')";

        }else if("getOoef".equals(inDto.getString("sqlName"))){
            String query = "SELECT * FROM OOEF_T WHERE OOEFENT =" + inDto.getBigDecimal("OOEFENT") + " AND OOEF001=''" + inDto.getString("OOEF001") +"''";
            sql = "SELECT OOEF001 FROM OPENQUERY(" + inDto.getString("ERP_Link")+",'"+query+"')";

        }
        return sql;
    }

    /**
     * 正式订单转ERP订单(gwai710)
     * @param inDto
     * @return
     */
    public JSONArray transfer710(Dto inDto){
        JSONArray json = new JSONArray();
        Date date = new Date();
        ShiroUser shiroUser = ShiroKit.getUser();
        String[] selectionIds = inDto.getString("datas").split(",");
        List list = Arrays.asList(selectionIds);
        Set set = new HashSet(list);
        String[] rid = (String[]) set.toArray(new String[0]);
        int rows = 0;
        for (String data : rid) {
            Dto inDto1 = Dtos.newDto();
            inDto1.put("gwcsdocno", data);
            inDto1.put("ent", shiroUser.getDBC());
            inDto1.put("lang", LangUtils.getLang(shiroUser.getLANG()));
            List<Dto> pList = this.gwcsTService.listGwcs032(inDto1);
            Boolean transFlag = true;
            for (int t = 0; t < pList.size(); t++) {
                List<Dto> gwcs_tPOs = this.gwcsTService.listGwcsInfo(inDto1);
                List<Dto> gwcsz_tPOs = this.gwcsTService.listGwcszInfo(inDto1);
                inDto1.put("gwak001", gwcs_tPOs.get(0).getString("GWAK001"));
                Dto gwakDto = Dtos.newDto();
                Dto adrDto = Dtos.newDto();
                try {
                    gwakDto = this.gwakTService.getGwakData(inDto1);
                } catch (Exception e) {
                    JSONObject jo = new JSONObject();
                    jo.put("ERPRESULT", "N");//同步结果  Y  N
                    jo.put("GWAK001", gwcs_tPOs.get(0).getString("GWAK001"));//客户编号
                    jo.put("GWAKL003", gwcs_tPOs.get(0).getString("GWAKL003_KH"));//客户名称
                    jo.put("GWCSDOCNO", gwcs_tPOs.get(0).getString("GWCSDOCNO"));//订单号
                    jo.put("REMARK", "getGwakData：" + e.getMessage());
                    jo.put("GWCS045", "");//订单号
                    json.add(jo);
                    continue;
                }
                try {
                    adrDto = this.gwcsTService.getAddress(inDto1);
                } catch (Exception e) {
                    JSONObject jo = new JSONObject();
                    jo.put("ERPRESULT", "N");//同步结果  Y  N
                    jo.put("GWAK001", gwcs_tPOs.get(0).getString("GWAK001"));//客户编号
                    jo.put("GWAKL003", gwcs_tPOs.get(0).getString("GWAKL003_KH"));//客户名称
                    jo.put("GWCSDOCNO", gwcs_tPOs.get(0).getString("GWCSDOCNO"));//订单号
                    jo.put("REMARK", "getAddress：" + e.getMessage());
                    jo.put("GWCS045", "");//订单号
                    json.add(jo);
                    continue;
                }
                Dto tcDto = Dtos.newDto();
                tcDto.put("XMDASITE", gwcs_tPOs.get(0).getString("GWCSPLANT"));
                tcDto.put("XMDAENT", inDto.getString("ENT"));
                tcDto.put("XMDADOCNO", DateUtils.formatDate(date, DateUtils.PATTERN_yyyyMMdd));
                tcDto.put("ERP_Link", inDto.getString("ERP_Link"));
                String sqlStr = this.generateSql710(tcDto,"getMaxXmdadocno");
                tcDto.put("sql", sqlStr);
                String dd01 = this.baseMapper.getMaxXmdadocno(tcDto);
                if (dd01 == null) {
                    dd01 = DateUtils.formatDate(date, DateUtils.PATTERN_yyyyMMdd) + "001";
                }
                //根据订单上的法人组织字段gwcsmlegal 从sys_org表找到ERP组织 根据ERP组织=MB001，从ERP的数据库DSCSYS的表DSCMB中抓到MB003的值。
                //Dto dbinfo1 = this.gwcsTService.getDBinfo1(shiroUser.getDBC(), gwcs_tPOs.get(0).getString("GWCSMLEGAL"));// 先查询biz_code_  因数据库排序问题  分成两个语句查询
                //Dto dbinfo2 = this.gwcsTService.getDBinfo2(dbinfo1.getString("BIZ_CODE"));
                // String dbname = dbinfo2.getString("MB001").trim();
                String dbname = gwcs_tPOs.get(0).getString("GWCSPLANT");
                //dbname = "NJNT";
                if (dbname.isEmpty()) { //没查到目标数据库  添加失败
                    JSONObject jo = new JSONObject();
                    jo.put("ERPRESULT", "N");//同步结果  Y  N
                    jo.put("GWAK001", gwcs_tPOs.get(0).getString("GWAK001"));//客户编号
                    jo.put("GWAKL003", gwcs_tPOs.get(0).getString("GWAKL003"));//客户名称
                    jo.put("GWCSDOCNO", gwcs_tPOs.get(0).getString("GWCSDOCNO"));//订单号
                    jo.put("REMARK", "订单没有归属法人");
                    jo.put("GWCS045", "");//订单号
                    json.add(jo);
                    continue;
                }

                //判断订单是否已经抛过  都是整单抛转 不需要项次
                Dto inDto2 = Dtos.newDto();
                inDto2.put("XMDASITE", dbname);
                inDto2.put("XMDAENT", inDto.getString("ENT"));
                inDto2.put("XMDA008", gwcs_tPOs.get(0).getString("GWCSDOCNO"));
                inDto2.put("ERP_Link", inDto.getString("ERP_Link"));
                String sqlStr2=this.generateSql710(inDto2,"getXmda008");
                inDto2.put("sql", sqlStr2);
                Dto checkinfo = this.baseMapper.getXmda008(inDto2);
                if (checkinfo != null) {
                    JSONObject jo = new JSONObject();
                    jo.put("ERPRESULT", "N");//同步结果  Y  N
                    jo.put("GWAK001", gwcs_tPOs.get(0).getString("GWAK001"));//客户编号
                    jo.put("GWAKL003", gwcs_tPOs.get(0).getString("GWAKL003_KH"));//客户名称
                    jo.put("GWCSDOCNO", gwcs_tPOs.get(0).getString("GWCSDOCNO"));//订单号
                    jo.put("REMARK", "订单已经抛转");
                    jo.put("GWCS045", "");//订单号
                    json.add(jo);
                    //该订单已经抛转过  同步失败  跳过进行下个订单
                    continue;
                }

                //判断客户编号在ERP中是否存在 不存在就新增一笔数据
                Dto inDto3 = Dtos.newDto();
                Dto outDto3 = Dtos.newDto();
                inDto3.put("PMAA001", gwcs_tPOs.get(0).getString("GWAK001"));
                inDto3.put("PMAAENT", inDto.getString("ENT"));
                inDto3.put("ERP_Link", inDto.getString("ERP_Link"));
                String sqlStr3=this.generateSql710(inDto3,"selectByGwak001");
                inDto3.put("sql", sqlStr3);
                outDto3 = this.baseMapper.selectByGwak001(inDto3);
                if (outDto3 == null) {
                    String syncresult = this.SyncERP(gwcs_tPOs.get(0).getString("GWAK001"), inDto.getString("ERP_Link"));
                    if (syncresult.equals("N")) {
                        JSONObject jo = new JSONObject();
                        jo.put("ERPRESULT", "N");//同步结果  Y  N
                        jo.put("GWAK001", gwcs_tPOs.get(0).getString("GWAK001"));//客户编号
                        jo.put("GWAKL003", gwcs_tPOs.get(0).getString("GWAKL003_KH"));//客户名称
                        jo.put("GWCSDOCNO", gwcs_tPOs.get(0).getString("GWCSDOCNO"));//订单号
                        jo.put("REMARK", "同步客户资料失败");
                        jo.put("GWCS045", "");//订单号
                        json.add(jo);
                        //同步客户资料失败  整张订单跳过 进行下个订单
                        continue;
                    }
                }

                try {
                    List<Dto> MD = new ArrayList<>();
                    for (Dto gwcs_tPO : gwcs_tPOs) {
                        //单身信息
                        Dto qDto = Dtos.newDto();
                        Dto jDto = Dtos.newDto();
                        qDto.put("ERP_Link",inDto.getString("ERP_Link"));
                        qDto.put("XMDCSITE", dbname);//目标数据库
                        qDto.put("XMDCENT", inDto.getString("ENT"));
                        //按法人组织抓取单别
                        Dto dhinfo = gwcsTService.getGwaz(inDto.getString("ENT"), gwcs_tPO.getString("GWCSMLEGAL"));
                        String TC001=dhinfo.getString("GWAZ002");//单别
                        String XMDCDOCNO=TC001+"-"+dd01;
                        qDto.put("XMDCDOCNO", XMDCDOCNO);
                        qDto.put("XMDCSEQ", gwcs_tPO.getString("GWCSSEQ"));
                        qDto.put("XMDC001", gwcs_tPO.getString("GWCS001"));//取CRM中购物车的品号(需要判断是否在ERP中是否存在?）
                        qDto.put("XMDC002", gwcs_tPO.getString("GWAML003")+" "+gwcs_tPO.getString("GWAML004"));
                        //qDto.put("TD007", gwcs_tPO.getString("GWCS113"));//仓库
                        qDto.put("XMDC006",gwcs_tPO.getString("GWCS002"));//销售单位
                        qDto.put("XMDC007", gwcs_tPO.getString("GWCS003"));//销售数量
                        qDto.put("XMDC008", gwcs_tPO.getString("GWCS002"));//参考单位
                        qDto.put("XMDC009", gwcs_tPO.getString("GWCS003"));//参考数量
                        qDto.put("XMDC010", gwcs_tPO.getString("GWCS002"));//计价单位
                        qDto.put("XMDC011", gwcs_tPO.getString("GWCS003"));//计价数量
                        //预计交货日期
                        if (gwcs_tPOs.get(0).getDate("GWCS016") != null) {
                            qDto.put("XMDC012", DateUtils.formatDate(gwcs_tPOs.get(0).getDate("GWCS016"), "yyyyMMdd"));
                        }
                        //预计签收日期
                        qDto.put("XMDC013", null);
                        //单价
                        qDto.put("XMDC015", gwcs_tPO.getString("GWCS115"));
                        //税种
                        qDto.put("XMDC016",gwcs_tPO.getString("GWCS032"));
                        //税率
                        if (gwcs_tPO.getBigDecimal("GWEA006") == null || gwcs_tPO.getBigDecimal("GWEA006").equals(new BigDecimal(0.00))) {
                            qDto.put("XMDC017", 0.16);
                        } else {
                            qDto.put("XMDC017", gwcs_tPO.getBigDecimal("GWEA006").divide(new BigDecimal(100), 4, RoundingMode.HALF_UP));//根据税种gwcs032抓税率
                        }
                        qDto.put("XMDC019", "1");//子件特性
                        qDto.put("XMDC020", "1");//紧急度
                        qDto.put("XMDC021", "N");//保税
                        qDto.put("XMDC022", "Y");//部分交货
                        qDto.put("XMDC023", "");//收货客户
                        qDto.put("XMDC024", "N");//多交期
                        qDto.put("XMDCUNIT", gwcs_tPO.getString("GWCSPLANT"));//出货据点
                        qDto.put("XMDCORGA", gwcs_tPO.getString("GWCSPLANT"));//收款据点

                        //qDto.put("TD012", gwcs_tPO.getString("GWCS005"));//原币税后金额
                        if (gwcs_tPO.getBigDecimal("GWCS034") == null) {
                            gwcs_tPO.put("GWCS034", 1);//汇率没有默认给1
                        }
                        //TD038：原币税前金额
                        if (gwcs_tPO.getBigDecimal("TD038") == null) {
                            //T100没有原币，全用本币
                            //qDto.put("TD038", "");//(GWCS040/(GWEA006/100)
                        } else {
                            //qDto.put("TD038", gwcs_tPO.getBigDecimal("GWCS005").subtract(gwcs_tPO.getBigDecimal("GWCS040").setScale(2, RoundingMode.HALF_UP)));//gwcs036-gwcs040
                            //本币税前金额
                            qDto.put("XMDC046", (gwcs_tPO.getBigDecimal("GWCS005").subtract(gwcs_tPO.getBigDecimal("GWCS040").setScale(2, RoundingMode.HALF_UP))).multiply(gwcs_tPO.getBigDecimal("GWCS034")));//gwcs036-gwcs040
                        }
                        //本币税后金额=原币税后金额*汇率
                        qDto.put("XMDC047", gwcs_tPO.getBigDecimal("GWCS005").multiply(gwcs_tPO.getBigDecimal("GWCS034")));
                        //GWCS040:原币税额
                        if (gwcs_tPO.getBigDecimal("GWCS040") == null) {
                            //T100没有原币，全用本币
                            //qDto.put("TD039", "");
                        } else {
                            //qDto.put("TD039", gwcs_tPO.getBigDecimal("GWCS040").setScale(2, RoundingMode.HALF_UP));
                            //本币税额
                            qDto.put("XMDC048", (gwcs_tPO.getBigDecimal("GWCS040").setScale(2, RoundingMode.HALF_UP)).multiply(gwcs_tPO.getBigDecimal("GWCS034")));
                        }

                        qDto.put("XMDC045", "1");//状态码
                        qDto.put("XMDC049", "");//理由码
                        qDto.put("XMDC050", gwcs_tPOs.get(0).getString("GWDC003"));//备注
                        qDto.put("XMDC052", "N");//检验
                        qDto.put("XMDC053", "");//留置理由码

                        qDto.put("XMDC027", "");//客户料号
                        qDto.put("XMDC028", "");//限定库位
                        qDto.put("XMDC029", "");//限定储位
                        qDto.put("XMDC030", "");//限定批号
                        qDto.put("XMDC031", "");//运输方式
                        qDto.put("XMDC032", "");//取货模式
                        qDto.put("XMDC033", "");//备品率
                        qDto.put("XMDC034", "");//可超交率
                        qDto.put("XMDC035", "");//价格核决
                        qDto.put("XMDC036", "");//专案编号
                        qDto.put("XMDC037", "");//WBS编号
                        qDto.put("XMDC038", "");//活动编号
                        qDto.put("XMDC039", "");//费用原因
                        qDto.put("XMDC040", "");//取价来源
                        qDto.put("XMDC041", "");//参考单号
                        qDto.put("XMDC042", "");//参考项次
                        qDto.put("XMDC043", "");//取出单价
                        qDto.put("XMDC044", "");//价差比
                        qDto.put("XMDC055", "");//来源单号
                        qDto.put("XMDC056", "");//来源项次


                        try {
                            this.execInsert(qDto,"XMDC_T");
                        } catch (Exception e) {
                            transFlag = false;
                            Dto inDto4 = Dtos.newDto();
                            inDto4.put("ERP_Link",inDto.getString("ERP_Link"));
                            inDto4.put("XMDCENT",inDto.getString("ENT"));
                            inDto4.put("XMDCSITE", dbname);
                            inDto4.put("XMDCDOCNO", XMDCDOCNO);
                            String delSql=this.generateSql710(inDto4,"deleteXmdc");
                            inDto4.put("sql", delSql);
                            this.baseMapper.deleteXmdc(inDto4);
                            JSONObject jo = new JSONObject();
                            jo.put("ERPRESULT", "N");//同步结果  Y  N
                            jo.put("GWAK001", gwcs_tPOs.get(0).getString("GWAK001"));//客户编号
                            jo.put("GWAKL003", gwcs_tPOs.get(0).getString("GWAKL003_KH"));//客户名称
                            jo.put("GWCSDOCNO", gwcs_tPOs.get(0).getString("GWCSDOCNO"));//订单号
                            jo.put("GWCS045", "");//订单号
                            jo.put("REMARK", "insertXmdc：" + e.getMessage());
                            json.add(jo);
                            //插入XMDC_T 失败  整张订单跳过 进行下个订单
                            break;
                        }

                        //更新
                        inDto1.put("gwcs102", gwcs_tPO.getString("GWCSSEQ"));
                        inDto1.put("gwcs045", XMDCDOCNO);
                        inDto1.put("gwcsacti", "Z");
                        //更新条件
                        inDto1.put("ent", shiroUser.getDBC());
                        inDto1.put("gwcsdocno",gwcs_tPO.getString("GWCSDOCNO"));
                        inDto1.put("gwcsseq", gwcs_tPO.getString("GWCSSEQ"));

                        try {
                            this.gwcsTService.update(inDto1);
                        } catch (Exception e) {
                            transFlag = false;
                            JSONObject jo = new JSONObject();
                            jo.put("ERPRESULT", "N");//同步结果  Y  N
                            jo.put("GWAK001", gwcs_tPOs.get(0).getString("GWAK001"));//客户编号
                            jo.put("GWAKL003", gwcs_tPOs.get(0).getString("GWAKL003_KH"));//客户名称
                            jo.put("GWCSDOCNO", gwcs_tPOs.get(0).getString("GWCSDOCNO"));//订单号
                            jo.put("GWCS045", "");//订单号
                            jo.put("REMARK", "update：" + e.getMessage());
                            json.add(jo);
                            //插入COPTD 失败  整张订单跳过 进行下个订单
                            break;
                        }
                    }
                    if (transFlag) {
                        //把赠品写入ERP单身
                        Integer seq = 9999;
                        for (Dto gwcsz_tPO : gwcsz_tPOs) {
                            //单身信息
                            Dto qDto = Dtos.newDto();

                            qDto.put("ERP_Link",inDto.getString("ERP_Link"));
                            qDto.put("XMDCSITE", dbname);//目标数据库
                            qDto.put("XMDCENT", inDto.getString("ENT"));
                            //按法人组织抓取单号
                            Dto dhinfo = gwcsTService.getGwaz(inDto.getString("ENT"), gwcs_tPOs.get(0).getString("GWCSMLEGAL"));
                            String TC001=dhinfo.getString("GWAZ002");//单别
                            String XMDCDOCNO=TC001+"-"+dd01;
                            qDto.put("XMDCDOCNO", XMDCDOCNO);
                            qDto.put("XMDCSEQ", seq);
                            qDto.put("XMDC001", gwcsz_tPO.getString("GWCSZ004"));//取CRM中订单赠品的品号(需要判断是否在ERP中是否存在?）
                            qDto.put("XMDC002", gwcsz_tPO.getString("GWAML003")+" "+gwcsz_tPO.getString("GWAML004"));
//                            qDto.put("TD007", gwcs_tPOs.get(0).getString("GWCS113"));//仓库
                            qDto.put("XMDC007", gwcsz_tPO.getString("GWCSZ005"));
                            qDto.put("XMDC008", gwcs_tPOs.get(0).getString("GWABL003")); //单位
                            qDto.put("XMDC015", 0);//单价
                            if (gwcs_tPOs.get(0).getDate("GWCS016") != null) {
                                qDto.put("XMDC012", DateUtils.formatDate(gwcs_tPOs.get(0).getDate("GWCS016"), "yyyyMMdd"));
                            }
                            qDto.put("XMDC045", "1");//状态码
                            qDto.put("XMDC049", "");//理由码
                            qDto.put("XMDC050", gwcs_tPOs.get(0).getString("GWDC003"));//备注
                            qDto.put("XMDC052", "N");//检验
                            qDto.put("XMDC053", "");//留置理由码

                            qDto.put("XMDC027", "");//客户料号
                            qDto.put("XMDC028", "");//限定库位
                            qDto.put("XMDC029", "");//限定储位
                            qDto.put("XMDC030", "");//限定批号
                            qDto.put("XMDC031", "");//运输方式
                            qDto.put("XMDC032", "");//取货模式
                            qDto.put("XMDC033", "");//备品率
                            qDto.put("XMDC034", "");//可超交率
                            qDto.put("XMDC035", "");//价格核决
                            qDto.put("XMDC036", "");//专案编号
                            qDto.put("XMDC037", "");//WBS编号
                            qDto.put("XMDC038", "");//活动编号
                            qDto.put("XMDC039", "");//费用原因
                            qDto.put("XMDC040", "");//取价来源
                            qDto.put("XMDC041", "");//参考单号
                            qDto.put("XMDC042", "");//参考项次
                            qDto.put("XMDC043", "");//取出单价
                            qDto.put("XMDC044", "");//价差比
                            qDto.put("XMDC055", "");//来源单号
                            qDto.put("XMDC056", "");//来源项次

                            try {
                                this.execInsert(qDto,"XMDC_T");
                            } catch (Exception e) {
                                transFlag = false;
                                Dto inDto5 = Dtos.newDto();
                                inDto5.put("ERP_Link",inDto.getString("ERP_Link"));
                                inDto5.put("XMDCENT",inDto.getString("ENT"));
                                inDto5.put("XMDCSITE", dbname);
                                inDto5.put("XMDCDOCNO", XMDCDOCNO);
                                String delSql=this.generateSql710(inDto5,"deleteXmdc");
                                inDto5.put("sql", delSql);
                                this.baseMapper.deleteXmdc(inDto5);
                                JSONObject jo = new JSONObject();
                                jo.put("ERPRESULT", "N");//同步结果  Y  N
                                jo.put("GWAK001", gwcs_tPOs.get(0).getString("GWAK001"));//客户编号
                                jo.put("GWAKL003", gwcs_tPOs.get(0).getString("GWAKL003_KH"));//客户名称
                                jo.put("GWCSDOCNO", gwcs_tPOs.get(0).getString("GWCSDOCNO"));//订单号
                                jo.put("GWCS045", "");//订单号
                                jo.put("REMARK", "insertXmdc：" + e.getMessage());
                                json.add(jo);
                                //插入COPTD 失败  整张订单跳过 进行下个订单
                                break;
                            }

                            inDto1.put("gwcszdocno", gwcsz_tPO.getString("GWCSZDOCNO"));
                            inDto1.put("gwcszent", gwcsz_tPO.getString("GWCSZENT"));
                            inDto1.put("gwcsz003", gwcsz_tPO.getString("GWCSZ003"));
                            inDto1.put("gwcszseq", seq);
                            seq--;
                            try {
                                this.gwcsTService.updateGWCSZ(inDto1);
                            } catch (Exception e) {
                                transFlag = false;
                                JSONObject jo = new JSONObject();
                                jo.put("ERPRESULT", "N");//同步结果  Y  N
                                jo.put("GWAK001", gwcs_tPOs.get(0).getString("GWAK001"));//客户编号
                                jo.put("GWAKL003", gwcs_tPOs.get(0).getString("GWAKL003_KH"));//客户名称
                                jo.put("GWCSDOCNO", gwcs_tPOs.get(0).getString("GWCSDOCNO"));//订单号
                                jo.put("GWCS045", "");//订单号
                                jo.put("REMARK", "updateGWCSZ：" + e.getMessage());
                                json.add(jo);
                                //插入COPTD 失败  整张订单跳过 进行下个订单
                                break;
                            }

                        }
                    }

                } catch (Exception e) {
                    transFlag = false;
                    JSONObject jo = new JSONObject();
                    jo.put("ERPRESULT", "N");//同步结果  Y  N
                    jo.put("GWAK001", gwcs_tPOs.get(0).getString("GWAK001"));//客户编号
                    jo.put("GWAKL003", gwcs_tPOs.get(0).getString("GWAKL003_KH"));//客户名称
                    jo.put("GWCSDOCNO", gwcs_tPOs.get(0).getString("GWCSDOCNO"));//订单号
                    jo.put("GWCS045", "");//订单号
                    jo.put("REMARK", "失败：" + e.getMessage());
                    json.add(jo);
                    //插入COPTD 失败  整张订单跳过 进行下个订单
                    continue;
                }

                //单头  订单信息
                Dto pDto = Dtos.newDto();

                pDto.put("ERP_Link",inDto.getString("ERP_Link"));
                pDto.put("XMDASITE", dbname);
                pDto.put("XMDAENT", inDto.getString("ENT"));
                //按法人组织抓取单别
                Dto dhinfo = gwcsTService.getGwaz(inDto.getString("ENT"), gwcs_tPOs.get(0).getString("GWCSMLEGAL"));
                String TC001=dhinfo.getString("GWAZ002");//单别
                String XMDADOCNO=TC001+"-"+dd01;
                pDto.put("XMDADOCNO", XMDADOCNO);
                pDto.put("XMDADOCDT", DateUtils.getDate("yyyyMMdd"));
                pDto.put("XMDA002", gwcs_tPOs.get(0).getString("GWCS014"));//业务人员
                pDto.put("XMDA003", gwcs_tPOs.get(0).getString("ERP_DEPT"));//业务部门
                pDto.put("XMDA004", gwcs_tPOs.get(0).getString("GWCS010"));//客户编号
                pDto.put("XMDA005", "1");//订单性质
                pDto.put("XMDA006", "1");//多角性质
                pDto.put("XMDA007", "3");//数据源（3：报价单）
                pDto.put("XMDA008", gwcs_tPOs.get(0).getString("GWCSDOCNO"));//来源单号
                pDto.put("XMDA009", gwakDto.getString("GWAK060"));//客户资料对应付款编号
                pDto.put("XMDA010", "");//交易条件

                //税种
                pDto.put("XMDA011", gwcs_tPOs.get(0).getString("GWAK007"));//按经销商gwcs011去客户档gwak抓税号gwak007
                //税率
                if (gwcs_tPOs.get(0).getBigDecimal("GWEA006") == null || gwcs_tPOs.get(0).getBigDecimal("GWEA006").equals(new BigDecimal(0.00))) {
                    pDto.put("XMDA012", 0.16);
                } else {
                    pDto.put("XMDA012", gwcs_tPOs.get(0).getBigDecimal("GWEA006").divide(new BigDecimal(100), 4, RoundingMode.HALF_UP));//根据税种gwcs032抓税率
                }
                pDto.put("XMDA013", "Y");//单价含税否
                pDto.put("XMDA015", gwcs_tPOs.get(0).getString("GWCS006"));//交易币别
                if (gwcs_tPOs.get(0).getBigDecimal("GWCS034") == null) {
                    gwcs_tPOs.get(0).put("GWCS034", 1);//汇率没有默认给1
                }
                pDto.put("XMDA016", gwcs_tPOs.get(0).getBigDecimal("GWCS034"));//汇率
                pDto.put("XMDA048", "");//内外销
                pDto.put("XMDA049", "");//汇率计算基准
                pDto.put("XMDA050", "");//多角流程编号
                pDto.put("XMDA035", "");//发票类型
                pDto.put("XMDA017", "");//取价方式
                pDto.put("XMDA018", "");//收款优惠条件
                pDto.put("XMDA052", "");//银行账户
                pDto.put("XMDA024", gwcs_tPOs.get(0).getString("GWCS010"));//账款客户
                pDto.put("XMDA022", gwcs_tPOs.get(0).getString("GWCS010"));//收货客户
                pDto.put("XMDA034", gwcs_tPOs.get(0).getString("GWCS010"));//最终客户
                pDto.put("XMDA203", gwcs_tPOs.get(0).getString("GWCS010"));//发票客户
                pDto.put("XMDA071", gwcs_tPOs.get(0).getString("GWCS050"));//订单备注
                //Dto yDto = this.baseMapper.getYewu(pDto);
                //if (yDto != null) {
                //    pDto.put("TC005", yDto.getString("MA015"));
                //    //pDto.put("TC006", yDto.getString("BIZ_CODE"));
                //}
                inDto1.put("GWCS010", gwcs_tPOs.get(0).getString("GWCS010"));
                if (adrDto != null) {
                    pDto.put("XMDA027", adrDto.getString("GWAL021"));
                    inDto1.put("flag", true);//抓取送货地址
                    Dto address = this.gwcsTService.getAddress(inDto1);
                    if (address != null) {
                        String address_ = address.getString("NAME010") + address.getString("NAME011")
                                + address.getString("NAME012") + address.getString("NAME013")
                                + address.getString("NAME014") + address.getString("NAME015")
                                + address.getString("NAME016") + address.getString("NAME017")
                                + address.getString("GWAL018");
                        pDto.put("XMDA025", address_);
                    }
                }



                pDto.put("XMDASTUS", "N");//状态码

                //几个需要求遍历订单求和的数据
                BigDecimal sum_TC029 = new BigDecimal(0);//订单金额(原币税前)
                BigDecimal sum_TC030 = new BigDecimal(0);//订单税额(原币)
                BigDecimal sum_TC031 = new BigDecimal(0);//订单总数量
                BigDecimal sum_TCI03 = new BigDecimal(0);//订单本币税前金额
                BigDecimal sum_TCI04 = new BigDecimal(0);//订单本币税额
                for (Dto gwcs_tPO : gwcs_tPOs) {
                    if (gwcs_tPO.getBigDecimal("TD038") != null) {
                        sum_TC029 = sum_TC029.add(gwcs_tPO.getBigDecimal("GWCS005").subtract(gwcs_tPO.getBigDecimal("GWCS040")));
                        sum_TC029 = sum_TC029.setScale(2, RoundingMode.HALF_UP);
                    }
                    if (gwcs_tPO.getBigDecimal("GWCS040") != null) {
                        sum_TC030 = sum_TC030.add(gwcs_tPO.getBigDecimal("GWCS040"));
                        sum_TC030 = sum_TC030.setScale(2, RoundingMode.HALF_UP);
                    }
                    if (gwcs_tPO.getBigDecimal("GWCS003") != null) {
                        sum_TC031 = sum_TC031.add(gwcs_tPO.getBigDecimal("GWCS003"));
                        sum_TC031 = sum_TC031.setScale(2, RoundingMode.HALF_UP);
                    }
                    if (gwcs_tPO.getBigDecimal("TDI01") != null) {
                        sum_TCI03 = sum_TCI03.add(gwcs_tPO.getBigDecimal("TDI01"));
                        sum_TCI03 = sum_TCI03.setScale(2, RoundingMode.HALF_UP);
                    }
                    if (gwcs_tPO.getBigDecimal("TDI04") != null) {
                        sum_TCI04 = sum_TCI04.add(gwcs_tPO.getBigDecimal("TDI04"));
                        sum_TCI04 = sum_TCI04.setScale(2, RoundingMode.HALF_UP);
                    }
                }
                pDto.put("XMDA042", sum_TC029);//sum（GWCS005-GWCS04O）
                pDto.put("XMDA043", sum_TC030);//sum（gwcs040）
                //pDto.put("TC031", sum_TC031);//sum（gwcs003）
                //
                //
                //if (adrDto != null) {
                //    pDto.put("TC074", adrDto.getString("GWAL020"));
                //    pDto.put("TC075", adrDto.getString("GWAL020"));//传真
                //}
                //pDto.put("TC200", "");//分销单头返利类型:无返利=2，有返利=1，铺货=2
                //if (gwcs_tPOs.get(0).getString("GWCS117").equals("1") || gwcs_tPOs.get(0).getString("GWCS117").equals("3")) {
                //    pDto.put("TC200", "1");
                //}
                //if (gwcs_tPOs.get(0).getString("GWCS117").equals("2") || gwcs_tPOs.get(0).getString("GWCS117").equals("4")) {
                //    pDto.put("TC200", "2");
                //}
                //if (gwcs_tPOs.get(0).getString("GWCS117").equals("5")) {
                //    pDto.put("TC200", "2");
                //}
                //pDto.put("TC201", "N");
                //pDto.put("TC202", "N");
                //交货日期
                //if (gwcs_tPOs.get(0).getDate("GWCS016") != null) {
                //    pDto.put("TCI01", DateFormatUtils.format(gwcs_tPOs.get(0).getDate("GWCS016"), "yyyyMMdd"));
                //    pDto.put("TCI02", DateFormatUtils.format(gwcs_tPOs.get(0).getDate("GWCS016"), "yyyyMMdd"));
                //}
                //
                //pDto.put("TCI03", sum_TCI03);//sum((GWCS005-GWCS040)*GWCS034)本币税前金额
                //pDto.put("TCI04", sum_TCI04);//sum(gwcs040*gwcs034)本币税额
                BigDecimal sum_XMDA212 = new BigDecimal(0);//订单本币税后金额
                sum_XMDA212=sum_XMDA212.add(sum_TCI03.add(sum_TCI04));
                pDto.put("XMDA212", sum_XMDA212);//订单本币税后金额
                //pDto.put("UDF12", gwcs_tPOs.get(0).getString("GWCS117"));
                //switch (gwcs_tPOs.get(0).getString("GWCS117")) {
                //    case "1":
                //        pDto.put("UDF12", "现款有返利");
                //        break;
                //    case "2":
                //        pDto.put("UDF12", "现款无返利");
                //        break;
                //    case "3":
                //        pDto.put("UDF12", "帐期有返利");
                //        break;
                //    case "4":
                //        pDto.put("UDF12", "帐期无返利");
                //        break;
                //    case "5":
                //        pDto.put("UDF12", "铺货有返利");
                //        break;
                //    case "6":
                //        pDto.put("UDF12", "铺货无返利");
                //        break;
                //}

                inDto1.put("gwcs045", XMDADOCNO);

                int row = 0;
                if (transFlag) {
                    try {
                        row = this.execInsert(pDto,"XMDA_T");

                    } catch (Exception e) {
                        e.printStackTrace();
                        JSONObject jo = new JSONObject();
                        jo.put("ERPRESULT", "N");//同步结果  Y  N
                        jo.put("GWAK001", gwcs_tPOs.get(0).getString("GWAK001"));//客户编号
                        jo.put("GWAKL003", gwcs_tPOs.get(0).getString("GWAKL003_KH"));//客户名称
                        jo.put("GWCSDOCNO", gwcs_tPOs.get(0).getString("GWCSDOCNO"));//订单号
                        jo.put("GWCS045", "");//订单号
                        jo.put("REMARK", "insertXmda：" + e.getMessage());
                        json.add(jo);
                        continue;
                    }
                }

                String result = "N";
                if (row > 0) {
                    result = "Y";
                }
                JSONObject jo = new JSONObject();
                jo.put("ERPRESULT", result);//同步结果  Y  N
                jo.put("GWAK001", gwcs_tPOs.get(0).getString("GWAK001"));//客户编号
                jo.put("GWAKL003", gwcs_tPOs.get(0).getString("GWAKL003_KH"));//客户名称
                jo.put("GWCSDOCNO", gwcs_tPOs.get(0).getString("GWCSDOCNO"));//订单号
                if (result == "Y") {
                    jo.put("GWCS045", XMDADOCNO);//ERP订单号
                    jo.put("REMARK", "");
                    json.add(jo);
                }
                /*if(result=="N"){
                    jo.put("REMARK","插入COPTC失败");
                }else {
                    jo.put("REMARK","");
                }*/
            }
            rows++;
        }
        return json;
    }

    /**
     * 生成拼接的sql字符串
     * @param inDto
     * @param sqlId
     * @return
     */
    private String generateSql710(Dto inDto,String sqlId){
        String sqlStr=null;
        String query=null;
        switch (sqlId) {
            case "getMaxXmdadocno":
                query="SELECT SUBSTR(XMDADOCNO,INSTR(XMDADOCNO,''-'')+1) XMDADOCNO FROM XMDA_T WHERE XMDAENT="
                        + inDto.getString("XMDAENT")+" AND XMDASITE=''"+inDto.getString("XMDASITE")
                        +"'' AND XMDADOCNO LIKE ''%"+inDto.getString("XMDADOCNO")+"%'' ";
                sqlStr = "SELECT CAST(CAST(MAX(XMDADOCNO) AS bigint)+1 AS CHAR(11)) XMDADOCNO FROM OPENQUERY("+inDto.getString("ERP_Link")
                        +",'"+query+ " ')";
                break;
            case "getXmda008":
                query="SELECT XMDA008 FROM XMDA_T WHERE XMDAENT="+inDto.getString("XMDAENT")+" AND XMDASITE=''"
                        +inDto.getString("XMDASITE")+"'' AND XMDA008=''"+inDto.getString("XMDA008")
                        +"'' AND XMDASTUS !=''X'' ";
                sqlStr = "SELECT * FROM OPENQUERY(" + inDto.getString("ERP_Link") + ",'" + query + " ')";
                break;
            case "selectByGwak001":
                query="SELECT PMAA001 FROM PMAA_T WHERE PMAAENT="+inDto.getString("PMAAENT")+" AND PMAA001=''"
                        +inDto.getString("PMAA001")+"'' ";
                sqlStr="SELECT * FROM OPENQUERY("+inDto.getString("ERP_Link")+",'"+query+" ')";
                break;
            case "getXmdkCount":
                query="SELECT COUNT(0) AS COUNT FROM XMDK_T WHERE XMDKENT="+inDto.getString("XMDKENT")
                        +" AND XMDKSITE=''"+inDto.getString("XMDKSITE")+"'' AND XMDK006=''"+inDto.getString("XMDK006")
                        +"'' ";
                sqlStr="SELECT * FROM OPENQUERY("+inDto.getString("ERP_Link")+",'"+query+" ')";
                break;
            case "getXmda":
                query="SELECT XMDADOCNO,XMDASTUS FROM XMDA_T WHERE XMDAENT="+inDto.getString("XMDAENT")+" AND XMDASITE=''"
                        +inDto.getString("XMDASITE")+"'' AND XMDA008=''"+inDto.getString("XMDA008")
                        +"'' AND XMDASTUS != ''X'' ";
                sqlStr = "SELECT * FROM OPENQUERY(" + inDto.getString("ERP_Link") + ",'" + query + " ')";
                break;
            case "updateXmda":
                sqlStr = "UPDATE OPENQUERY("+inDto.getString("ERP_Link")+",'SELECT XMDASTUS FROM XMDA_T WHERE XMDAENT="
                        +inDto.getString("XMDAENT")
                        +" AND XMDASITE=''"+inDto.getString("XMDASITE")
                        +"'' AND XMDADOCNO=''"+inDto.getString("XMDADOCNO")
                        +"'' AND XMDASTUS!=''X''"
                        +" AND XMDA008=''"+inDto.getString("XMDA008")
                        +"'' ') SET XMDASTUS='X'";
                break;
            case "deleteXmda":
                sqlStr="DELETE OPENQUERY("+inDto.getString("ERP_Link")+",'SELECT * FROM XMDA_T WHERE XMDAENT=''"
                        + inDto.getString("XMDAENT")+"'' AND XMDASITE=''"+inDto.getString("XMDASITE")
                        +"'' AND XMDADOCNO=''"+inDto.getString("XMDADOCNO")
                        +"'' ')";
                break;
            case "deleteXmdc":
                sqlStr="DELETE OPENQUERY("+inDto.getString("ERP_Link")+",'SELECT * FROM XMDC_T WHERE XMDCENT=''"
                        + inDto.getString("XMDCENT")+"'' AND XMDCSITE=''"+inDto.getString("XMDCSITE")
                        +"'' AND XMDCDOCNO=''"+inDto.getString("XMDCDOCNO")
                        +"'' ')";
                break;
            case "deleteXmdd":
                sqlStr="DELETE OPENQUERY("+inDto.getString("ERP_Link")+",'SELECT * FROM XMDD_T WHERE XMDDENT=''"
                        + inDto.getString("XMDDENT")+"'' AND XMDDSITE=''"+inDto.getString("XMDDSITE")
                        +"'' AND XMDDDOCNO=''"+inDto.getString("XMDDDOCNO")
                        +"'' ')";
                break;
        }
        return sqlStr;
    }


    /**
     * 客户资料同步
     */
    public String SyncERP(String gwak001, String ERP_Link) {
        ShiroUser shiroUser = ShiroKit.getUser();

        //获取gwak001对应的客户资料数据
        Dto qDto = Dtos.newDto();
        qDto.put("ent", shiroUser.getDBC());
        qDto.put("gwak001", gwak001);
        Dto info = this.gwakTService.getGwakData(qDto);

        //获取目标数据库
        //Dto dbinfo = this.gwakTService.getDBinfo(MB001);
        Dto outDto = Dtos.newDto();
        //outDto.put("MB001", dbinfo.getString("MB001").trim());//获取目标数据库
        outDto.put("ERP_Link", ERP_Link);
        outDto.put("PMAAENT", shiroUser.getDBC());
        outDto.put("PMAA001", info.getString("GWAK001"));
//        outDto.put("PMAA002", info.getString("GWAK002"));//交易对象类型
//        outDto.put("MA002", info.getString("GWAKL003"));
//        outDto.put("MA003", info.getString("GWAKL004"));
        outDto.put("PMAA016", info.getString("GWAK050"));//负责人
//        outDto.put("MA005", info.getString("GWAK031"));//联系人
//        outDto.put("MA006", info.getString("GWAK030"));//电话1
        //outDto.put("MA007", info.getString("GWAK050"));//电话2
        //outDto.put("MA010", info.getString("GWAK007"));
        if (info.getString("GWAK051").equals(null)) {//资本额
            outDto.put("PMAA018", "");
        } else {
            outDto.put("PMAA018", info.getBigDecimal("GWAK051"));
        }
        if (info.getString("GWAK052").equals(null)) {//年营收
            outDto.put("PMAA021", "");
        } else {
            outDto.put("PMAA021", info.getBigDecimal("GWAK052"));
        }
        outDto.put("PMAA011", info.getString("GWAK008"));//交易币别
//        outDto.put("MA017", info.getString("GWAK023"));//省
//        outDto.put("MA018", info.getString("GWAK024"));//市
//        outDto.put("MA019", info.getString("GWAK021"));//国
//        outDto.put("MA023", info.getString("GWAK028"));//详细地址/注册地址
//        if (!(info.getString("GWAL018_fp").isEmpty())) {
//            outDto.put("MA025", info.getString("GWAL018_fp"));//gwal018 where gwal003='I' 发票地址
//        }
//        if (!(info.getString("GWAL018_sh").isEmpty())) {
//            outDto.put("MA027", info.getString("GWAL018_sh"));//gwal018 where gwal003='D' 送货地址
//        }
//        outDto.put("MA031", info.getString("GWAK060_NAME"));//付款条件
//        outDto.put("OCC62", "N"); // 信用额度控制
        outDto.put("PMAA055", 0);   // 信用额度
        outDto.put("PMAA056", 0);   // 信用额度容许超出比率
//        outDto.put("OCC44", "2"); // 计价方式
//        outDto.put("OCC1028", 0);   // 折扣率
//        outDto.put("OCC08", "A"); // 发票种类 (发票别？)
        //outDto.put("MA038", info.getString("GWAK012"));//税种
//        outDto.put("OCC41", "1"); //税种
//        outDto.put("MA039", "1"); // 单据发送方式
        outDto.put("PMAA206", "2"); // 结算方式
//        outDto.put("MA042", "1"); // 票据寄领
//        outDto.put("MA044", 0);  // 预计收款日
//        outDto.put("MA045", 0);  // 资金实现日
//        outDto.put("MA047", "112201"); //账款科目
        //outDto.put("MA048", "1");//运输方式
//        outDto.put("OCC53", 0);  // 佣金比率
//        outDto.put("MA060", 0);  // 其它比率
//        outDto.put("MA061", 0);  // 保险费率
//        outDto.put("MA062", ""); // 文件地址
//        outDto.put("MA066", "N"); // 总公司付款
//        outDto.put("MA067", 0);  // 分店数
//        outDto.put("MA074", "1121"); // 票据科目
//        outDto.put("MA075", "86");  // 定价顺序
//        outDto.put("MA082", "N");   // 信用额度由总公司控制 Y/N
//        outDto.put("MA083", info.getString("GWAK060")); //付款条件
//        outDto.put("MA084", "N");  // 发票号码由总公司控制
//        outDto.put("MA086", "N");  // 预留字段
//        outDto.put("MA087", "2");  // 税额
//        outDto.put("MA088", "1");  // 订单信用检查方式
//        outDto.put("MA089", "1");  // 销货信用检查方式
//        outDto.put("MA090", 1);    // LC收状金额比率
//        outDto.put("MA091", 1);    // 未兑现应收票据比率
//        outDto.put("MA092", 1);    // 应收账款比率
//        outDto.put("MA093", 1);    // 未开票销货金额比率
//        outDto.put("MA094", 1);    // 未出货订单金额比率
//        outDto.put("OCC246"," ");
//        outDto.put("OCCPOS","1");
//        outDto.put("OCC73"," ");
//        outDto.put("OCC71","1");
//        outDto.put("OCC72", 0);    // 订金比率
//        outDto.put("MA096", "1");  // 开票方法
//        outDto.put("MA097", "1");  // 核准状况
        //抓税率
//        if (info.getString("GWEA006") == null || info.getString("GWAK004").isEmpty()) {
//            outDto.put("MA101", 0.16);
//        } else {
//            outDto.put("MA101", info.getBigDecimal("GWEA006"));
//        }
//        outDto.put("MA103", "1");//出货通知信用检查方式
//        outDto.put("MA104", 0);//未销货出货通知金额比率
//        outDto.put("MA105", "220301");//预收账款科目
//        outDto.put("MA106", "N");//汇至EBC
//        outDto.put("MA109", 0);//预留字段
//        outDto.put("MA110", 0);//预留字段
//        outDto.put("MA111", 0);//预留字段
//        outDto.put("MA113", "N");//EBC汇出码

        Dto lDto= Dtos.newDto();
        lDto.put("ERP_Link", ERP_Link);
        lDto.put("PMAALENT", shiroUser.getDBC());
        lDto.put("PMAAL001",info.getString("GWAK001"));
        lDto.put("PMAAL002",LangUtils.getLang(shiroUser.getLANG()));
        lDto.put("PMAAL003",info.getString("GWAKL004"));
        lDto.put("PMAAL004",info.getString("GWAKL003"));
        lDto.put("PMAAL005"," ");
        //暂时直接写入Y
        //String result = "Y";
        String result = "N";
        //将客户资料插入指定ERP数据库
        int i = this.execInsert(outDto,"PMAA_T");
        this.execInsert(lDto,"PMAAL_T");
        if (i > 0) {
            result = "Y";
        }
        return result;
    }

    /**
     * ERP订单还原
     * @param inDto
     * @return
     */
    public Dto restore710(Dto inDto){
        Dto outDto = Dtos.newDto();
        ShiroUser shiroUser = ShiroKit.getUser();
        String[] selectionIds = inDto.getString("datas").split(",");
        List list = Arrays.asList(selectionIds);
        Set set = new HashSet(list);
        String[] rid = (String[]) set.toArray(new String[0]);
        int rows = 0;
        String err_message = "";
        for (String data : rid) {
            Dto inDto1 = inDto;
            inDto1.put("GWCSDOCNO", data);
            List<Dto> gwcs = this.gwcsTService.getGWCS045(inDto1);
            Boolean flag1 = this.gwcsTService.getGwdfCount(inDto1);
            Boolean flag2 = false;
            for (Dto tDto : gwcs) {
                tDto.put("ERP_Link",inDto.getString("ERP_Link"));
                tDto.put("XMDKENT",inDto.getString("ENT"));
                tDto.put("XMDKSITE",tDto.getString("GWCSPLANT"));
                tDto.put("XMDK006",tDto.getString("GWCS045"));
                String sqlStr4=this.generateSql710(tDto,"getXmdkCount");
                tDto.put("sql", sqlStr4);
                Dto result = this.baseMapper.getXmdkCount(tDto);
                if (result.getBigDecimal("COUNT").compareTo(new BigDecimal(0)) == 1) {
                    flag2 = true;
                    break;
                }
            }
            if (flag1 || flag2) {
                err_message = data + ',' + err_message;
            }
        }
        err_message = StringUtils.substringBeforeLast(err_message, ",");
        if (!("").equals(err_message)) {
            outDto.setAppCode(300);
            outDto.put("docno","订单" + err_message + "已做过出货单或变更单，无法撤销！");
        }
        for (String data : rid) {
            Dto inDto2 = Dtos.newDto();
            inDto2.put("ent",inDto.getString("ENT"));
            inDto2.put("gwcsdocno",data);
            List<Dto> pList = this.gwcsTService.listGwcs032(inDto2);
            for (int t = 0; t < pList.size(); t++) {
                List<Dto> gwcs_tPOs = this.gwcsTService.listGwcsInfo(inDto2);

                //根据订单上的法人组织字段gwcsmlegal 从sys_org表找到ERP组织 根据ERP组织=MB001，从ERP的数据库DSCSYS的表DSCMB中抓到MB003的值。
                //Dto dbinfo1 = this.gwcsTService.getDBinfo1(shiroUser.getDBC(), gwcs_tPOs.get(0).getString("GWCSMLEGAL"));// 先查询biz_code_  因数据库排序问题  分成两个语句查询
                //Dto dbinfo2 = this.gwcsTService.getDBinfo2(dbinfo1.getString("BIZ_CODE"));
                //String dbname = dbinfo2.getString("MB001").trim();
                String dbname = gwcs_tPOs.get(0).getString("GWCSPLANT");

                //dbname = "NJNT";
                inDto2.put("ERP_Link", inDto.getString("ERP_Link"));
                inDto2.put("XMDAENT", inDto.getString("ENT"));
                inDto2.put("XMDASITE", dbname);
                inDto2.put("XMDA008", data);
                String sqlStr = this.generateSql710(inDto2,"getXmda");
                inDto2.put("sql", sqlStr);
                Dto XMDA_INFO = this.baseMapper.getXmda(inDto2);
                if (XMDA_INFO == null) {
                    GwcsT gwcsT = new GwcsT();
                    gwcsT.setGWCSACTI("Y");
                    gwcsT.setGWCSENT(shiroUser.getDBC());
                    gwcsT.setGWCSDOCNO(gwcs_tPOs.get(0).getString("GWCSDOCNO"));
                    gwcsT.setGWCS045("  ");
                    this.gwcsTService.updateGwcs(gwcsT);
                    outDto.setAppCode(500);
                    outDto.put("docno", "找不到对应ERP订单");
                } else {
                    Dto inDto3 = Dtos.newDto();
                    inDto3.put("ERP_Link", inDto.getString("ERP_Link"));
                    inDto3.put("XMDAENT", inDto.getString("ENT"));
                    inDto3.put("XMDASITE", dbname);
                    inDto3.put("XMDADOCNO", XMDA_INFO.getString("XMDADOCNO"));
                    inDto3.put("XMDA008", data);
                    inDto3.put("XMDASTUS", "X");
                    inDto3.put("XMDCDOCNO", XMDA_INFO.getString("XMDADOCNO"));
                    inDto3.put("XMDCSTUS", "X");

                    String sqlStr2 = this.generateSql710(inDto3, "updateXmda");
                    inDto3.put("sql", sqlStr2);
                    this.baseMapper.updateXmda(inDto3);

                    GwcsT gwcsT = new GwcsT();
                    gwcsT.setGWCSACTI("Y");
                    gwcsT.setGWCSENT(shiroUser.getDBC());
                    gwcsT.setGWCSDOCNO(gwcs_tPOs.get(0).getString("GWCSDOCNO"));
                    //gwcsT.setGWCS045(COPTCinfo.getString("TC002"));
                    gwcsT.setGWCS045("  ");
                    this.gwcsTService.updateGwcs(gwcsT);
                    outDto.setAppCode(200);
                    outDto.put("docno", "操作成功");
                } /*else if (COPTCinfo.getString("TC027").equals("Y")) {
                    outDto.put("docno", "ERP订单已经审核不能还原");
                }*/
            }
            rows++;
        }
        return outDto;
    }


    /**
     * 维修费用收入还原订单(gwei025)
     */
    public Dto restore025(Dto inDto) {
        Dto outDto = Dtos.newDto();
        ShiroUser shiroUser = ShiroKit.getUser();
        String[] selectionIds = inDto.getString("datas").split(",");
        List list = Arrays.asList(selectionIds);
        Set set = new HashSet(list);
        String[] rid = (String[]) set.toArray(new String[0]);
        int rows = 0;
        for (String data : rid) {
            inDto.put("MMRXDOCNO", data);
            //根据单号查询维修费用结算表数据
            List<Dto> mmrxData = this.mmrxTService.getMmrxAllData(inDto);

            inDto.put("XMDA008", data);
            inDto.put("XMDAENT",shiroUser.getDBC());
            inDto.put("XMDASITE",mmrxData.get(0).getString("MMRXPLANT"));
            inDto.put("XMDASTUS", "X");
            Dto xmdaInfo = this.getXmda008(inDto);
            if (xmdaInfo == null) {
                MmrxT mmrxT = new MmrxT();
                mmrxT.setMMRXACTI("Y");
                mmrxT.setMMRX029("");
                UpdateWrapper mmrxTUpdateWrapper = new UpdateWrapper();
                mmrxTUpdateWrapper.eq("MMRXSENT",shiroUser.getDBC());
                mmrxTUpdateWrapper.eq("MMRXDOCNO",data);
                mmrxT.update(mmrxTUpdateWrapper);
                outDto.put("docno", "找不到对应ERP订单");
            } else if (xmdaInfo.getString("XMDASTUS").equals("N")) { // 未审核订单才可撤回
                Dto inDto2 = Dtos.newDto();
                inDto2.put("ERP_Link", inDto.getString("ERP_Link"));
                inDto2.put("XMDAENT",shiroUser.getDBC());
                inDto2.put("XMDASITE",mmrxData.get(0).getString("MMRXPLANT"));
                inDto2.put("XMDASTUS", "X"); // 将该笔订单作废掉
                inDto2.put("XMDADOCNO", xmdaInfo.getString("XMDADOCNO"));
                // 更新订单状态
                int count = this.updateXmdaStatus(inDto2);
                if(count == 0 ) {
                    outDto.put("docno", "系统错误，ERP更新失败");
                }else {
                    MmrxT mmrxT = new MmrxT();
                    mmrxT.setMMRXACTI("Y");
                    mmrxT.setMMRX029("");
                    UpdateWrapper mmrxTUpdateWrapper = new UpdateWrapper();
                    mmrxTUpdateWrapper.eq("MMRXSENT",shiroUser.getDBC());
                    mmrxTUpdateWrapper.eq("MMRXDOCNO",data);
                    mmrxT.update(mmrxTUpdateWrapper);
                    outDto.put("docno", "操作成功");
                }
            } else if (xmdaInfo.getString("XMDASTUS").equals("Y")) {
                outDto.put("docno", "ERP单据已经审核不能还原");
            }
            rows++;
        }
        return outDto;
    }


    /**
     * 维修费用收入转ERP订单(gwei025)
     * @param inDto
     * @return
     */
    public JSONArray transfer025(Dto inDto) {
        ShiroUser shiroUser = ShiroKit.getUser();
        // 获取前台多选的维修费用收入ID
        String[] selectionIds = inDto.getString("datas").split(",");
        List list = Arrays.asList(selectionIds);
        // 对ID进行去重
        Set set = new HashSet(list);
        String[] rid = (String[]) set.toArray(new String[0]); // 这里加 new String[0] 是为了能够强转String[]

        // 最后返回的JSON数据
        JSONArray json = new JSONArray();

        for (String data : rid) {

            inDto.put("MMRXDOCNO", data);
            //根据单号查询维修收入结算表数据
            List<Dto> mmrx_tPOs = this.mmrxTService.getMmrxAllData(inDto);

            // 数据库主机
            String ERP_Link = inDto.getString("ERP_Link");
            String ENT = shiroUser.getDBC();
            String SITE = mmrx_tPOs.get(0).getString("MMRXPLANT");

            //（根据客户订单号）判断订单是否已经抛过  都是整单抛转 不需要项次
            Dto inDto3 = Dtos.newDto();
            inDto3.put("ERP_Link",ERP_Link);
            inDto3.put("XMDAENT", ENT);
            inDto3.put("XMDASITE",SITE);
            inDto3.put("XMDA008", mmrx_tPOs.get(0).getString("MMRXDOCNO"));
            Dto checkinfo = this.getXmda008(inDto3);
            if(checkinfo != null && checkinfo.getString("XMDA008") != null) {
                this.handleExceptionBy025(mmrx_tPOs.get(0),json);
                //该订单已经抛转过  同步失败  跳过进行下个订单
                continue;
            }

            //判断客户编号在ERP中是否存在 不存在就新增一笔客户数据
            Dto inDto2 = Dtos.newDto();
            inDto2.put("PMAA001", mmrx_tPOs.get(0).getString("MMRX018"));
            inDto2.put("ERP_Link", ERP_Link);
            inDto2.put("PMAAENT",ENT);
            inDto2.put("sql",this.generateSql710(inDto2,"selectByGwak001"));
            Dto outDto2 = this.baseMapper.selectExecSql(inDto2);
            //  客户不存在，将客户资料同步到ERP
            if (outDto2 == null || outDto2.getString("PMAA001").isEmpty()) {
                String syncresult = this.SyncERP(inDto2.getString("PMAA001"),ERP_Link);
                if (!syncresult.equals("Y")) {
                    this.handleExceptionBy025(mmrx_tPOs.get(0),json);
                    //同步客户资料失败  整张订单跳过 进行下个订单
                    continue;
                }
            }

            Dto dhinfo = this.mmrxTService.getGwaz(mmrx_tPOs.get(0).getString("MMRXLEGAL"));
            String pre = dhinfo.getString("GWAZ002") + "-";
            // 获取最大单号
            Date date = new Date();
            Dto tcDto = Dtos.newDto();
            tcDto.put("ERP_Link", inDto.getString("ERP_Link"));
            tcDto.put("XMDAENT",ENT);
            tcDto.put("XMDASITE",SITE);
            tcDto.put("XMDADOCNO", DateUtils.formatDate(date, DateUtils.PATTERN_yyyyMMdd));
            tcDto.put("sql",this.generateSql710(tcDto,"getMaxXmdadocno"));
            String dd01;
            Dto dd01Dto = this.baseMapper.selectExecSql(tcDto);
            if (dd01Dto == null) {
                dd01 = pre + DateUtils.formatDate(date, DateUtils.PATTERN_yyyyMMdd) + "001";
            }else {
                dd01 = pre + dd01Dto.getString("XMDADOCNO");
            }


            Dto infoDto = Dtos.newDto();

            infoDto.put("ERP_Link",ERP_Link);
            infoDto.put("dd01",dd01);
            infoDto.put("ENT",ENT);
            infoDto.put("SITE",mmrx_tPOs.get(0).getString("MMRXPLANT"));

            // 新增订单单身明细
            try {
                this.insertXmdcBy025(mmrx_tPOs,infoDto);
            } catch (Exception e) {
                // 记录失败信息
                this.handleExceptionBy025(mmrx_tPOs.get(0),json);
                // 删除已添加的记录
                Dto exceDto = Dtos.newDto();
                exceDto.putAll(inDto);
                exceDto.put("XMDCDOCNO",dd01);
                exceDto.put("XMDCENT",ENT);
                exceDto.put("XMDCSITE",SITE);

                exceDto.put("sql",this.generateSql710(exceDto,"deleteXmdc"));
                this.baseMapper.deleteExecSql(exceDto);
                // 更新来源订单状态
                this.updateMmrx(data);

                e.printStackTrace();
                continue;
            }

            // 新增交期明细
            try {
                this.insertXmddBy025(mmrx_tPOs,infoDto);
            } catch (Exception e) {
                // 记录失败信息
                this.handleExceptionBy025(mmrx_tPOs.get(0),json);
                // 删除已添加的记录
                Dto exceDto = Dtos.newDto();
                exceDto.putAll(inDto);
                exceDto.put("XMDDDOCNO",dd01);
                exceDto.put("XMDDENT",ENT);
                exceDto.put("XMDDSITE",SITE);
                exceDto.put("sql",this.generateSql710(exceDto,"deleteXmdd"));
                this.baseMapper.deleteExecSql(exceDto);
                // 更新来源订单状态
                this.updateMmrx(data);

                e.printStackTrace();
                continue;
            }

            // 新增单头
            try {
                Dto mmrx_tPO = mmrx_tPOs.get(0);
                this.insertXmdaBy025(mmrx_tPO,infoDto,json);
            } catch (Exception e) {
                // 记录失败信息
                this.handleExceptionBy025(mmrx_tPOs.get(0),json);
                // 删除已添加的记录
                Dto exceDto = Dtos.newDto();
                exceDto.putAll(inDto);
                exceDto.put("XMDADOCNO",dd01);
                exceDto.put("XMDAENT",ENT);
                exceDto.put("XMDASITE",SITE);
                exceDto.put("sql",this.generateSql710(exceDto,"deleteXmda"));
                this.baseMapper.deleteExecSql(exceDto);
                // 更新来源订单状态
                this.updateMmrx(data);

                e.printStackTrace();
                continue;
            }
        }
        return json;
    }

    /**
     * 维修费用收入转ERP订单(gwei025) : 增加单头
     * @param infoDto
     * @return
     */
    private void insertXmdaBy025(Dto mmrx_tPO,Dto infoDto,JSONArray json) {
        //单头  订单信息
        Dto pDto = Dtos.newDto();
        pDto.put("ERP_Link", infoDto.getString("ERP_Link"));

        pDto.put("XMDAENT",infoDto.getString("ENT"));
        pDto.put("XMDASITE",mmrx_tPO.getString("MMRXPLANT"));
        pDto.put("XMDADOCNO", infoDto.getString("dd01"));
        pDto.put("XMDADOCDT", DateUtils.getDate("yyyyMMdd")); // 订单日期（当前日期）
        pDto.put("XMDA001", 0); // 版次
        pDto.put("XMDA002", mmrx_tPO.getString("MMRX022_ERP")); // 业务人员
        pDto.put("XMDA003", mmrx_tPO.getString("MMRX032_ERP")); // 部门编号
        pDto.put("XMDA004", mmrx_tPO.getString("MMRX018")); // 客户编号
        pDto.put("XMDA005", 1); // 订单性质（默认1 ：一般订单）
        pDto.put("XMDA006", 1); // 多角性质（默认1 ：一般交易）
        pDto.put("XMDA007", "M"); // 来源（默认M）
        pDto.put("XMDA008", mmrx_tPO.getString("MMRXDOCNO")); // 来源单号
        pDto.put("XMDA009", mmrx_tPO.getString("GWAK060")); // 收款条件
        pDto.put("XMDA010", mmrx_tPO.getString("GWAK015")); // 交易条件
//                pDto.put("OEA11", "M");//订单来源
//                pDto.put("TC054", mmrx_tPO.getString("MMRX018_NAME"));//客户名称
//                pDto.put("OEA57", "01"); // 出货工厂 ( 暂定为OEA57：出货仓库 )
        pDto.put("XMDA015", mmrx_tPO.getString("MMRX006")); // 交易币种
        pDto.put("XMDA011", mmrx_tPO.getString("MMRX007"));// 税种
        pDto.put("XMDA016", mmrx_tPO.getString("MMRX009")); // 汇率
        pDto.put("XMDA021", mmrx_tPO.getString("MMRX018")); // 账款客户
        pDto.put("XMDA022", mmrx_tPO.getString("MMRX018")); // 收货客户
        pDto.put("XMDA034", mmrx_tPO.getString("MMRX018")); // 最终客户
        pDto.put("XMDA203", mmrx_tPO.getString("MMRX018")); // 发票客户
        pDto.put("XMDA013", "Y"); // 单价含税否
        pDto.put("XMDA027", mmrx_tPO.getString("MMRX022")); // 联系人
        pDto.put("XMDA048", 1); // 订单性质（默认1：内销）

//                if(mmrx_tPO.getString("MMRX025").split(";").length > 0){ // 送货地址
//                    pDto.put("OEA044", mmrx_tPO.getString("MMRX025").split(";")[0]);
//                }
        pDto.put("XMDA020", "1"); // 运输方式
        pDto.put("XMDASTUS", "N"); // 审核码
        pDto.put("XMDA071", mmrx_tPO.getString("MMRX031"));// 备注

        Dto sumData = this.mmrxTService.getSumData(mmrx_tPO);
        BigDecimal GWEA006 = mmrx_tPO.getBigDecimal("GWEA006");
        BigDecimal MMRX014_SUM = mmrx_tPO.getBigDecimal("MMRX014_SUM");
        BigDecimal MMRX016_SUM = mmrx_tPO.getBigDecimal("MMRX016_SUM");
        // 税率
        if (GWEA006 == null || GWEA006.equals(new BigDecimal(0.00))) {
            pDto.put("XMDA012", 0.16);
        } else {
            pDto.put("XMDA012", mmrx_tPO.getBigDecimal("GWEA006").divide(new BigDecimal(100), 4, RoundingMode.HALF_UP));//根据税种gwcs032抓税率
        }

        // 订单总未税金额
        if(mmrx_tPO.getBigDecimal("TDI01") == null) {
            pDto.put("XMDA041",new BigDecimal(0.00));
        }else {
            pDto.put("XMDA041",mmrx_tPO.getBigDecimal("TDI01").setScale(2, RoundingMode.HALF_UP));
        }
        // 订单总含税金额
        if(MMRX014_SUM == null || MMRX014_SUM.equals(new BigDecimal(0.00))) {
            pDto.put("XMDA042", new BigDecimal(0.00));
        }else {
            pDto.put("XMDA042", sumData.getBigDecimal("MMRX014_SUM").setScale(2, RoundingMode.HALF_UP)); //sum（gwcs036-gwcs040） 订单金额
        }
        // 订单总税额
        if(MMRX016_SUM == null || MMRX016_SUM.equals(new BigDecimal(0.00))) {
            pDto.put("XMDA043", new BigDecimal(0.00));
        }else {
            pDto.put("XMDA043", sumData.getBigDecimal("MMRX014_SUM").setScale(2, RoundingMode.HALF_UP)); //sum（gwcs036-gwcs040） 订单金额
        }

        int row = this.execInsert(pDto,"XMDA_T");

        String result = "N";
        if (row > 0) {
            result = "Y";
        }
        JSONObject jo = new JSONObject();
        jo.put("ERPRESULT", result);//同步结果  Y  N
        jo.put("GWAK001", mmrx_tPO.getString("MMRX018"));//客户编号
        jo.put("GWAKL003",  mmrx_tPO.getString("MMRX018_NAME"));//客户名称
        jo.put("MMRXDOCNO",  mmrx_tPO.getString("MMRXDOCNO"));//订单号
        json.add(jo);
    }

    /**
     * 维修费用收入转ERP订单(gwei025) : 增加单身明细
     * @param mmrx_tPOs
     * @return
     */
    private void insertXmdcBy025(List<Dto> mmrx_tPOs,Dto infoDto) {
        for (Dto mmrx_tPO : mmrx_tPOs) {
            //单身信息
            Dto qDto = Dtos.newDto();
            qDto.put("ERP_Link", infoDto.getString("ERP_Link"));
            //按法人组织抓取单号
            DecimalFormat mFormat = new DecimalFormat("0000");//确定格式，把1 转换为0001
            String mmrxseq = mFormat.format(mmrx_tPO.getBigDecimal("MMRXSEQ"));
            qDto.put("XMDCDOCNO", infoDto.getString("dd01"));
            qDto.put("XMDCSEQ", mmrxseq);
            qDto.put("XMDCENT",infoDto.getString("ENT"));
            qDto.put("XMDC001", mmrx_tPO.getString("MMRX001"));//取CRM中购物车的品号(需要判断是否在ERP中是否存在?）

//                    qDto.put("OEB06", mmrx_tPO.getString("GWAML003") + " " + mmrx_tPO.getString("GWAML004")); // 品名/规格
//                    qDto.put("OEB09", mmrx_tPO.getString("GWAM019"));  // 仓库
            qDto.put("XMDC007", mmrx_tPO.getString("MMRX003"));  // 订单数量
            if(mmrx_tPO.getString("MMRX003") == null || mmrx_tPO.getString("MMRX003").equals("")) {
                qDto.put("XMDC009", 0);  // 参考数量
                qDto.put("XMDC011", 0);  // 计价数量
            }else {
                qDto.put("XMDC009", mmrx_tPO.getString("MMRX003"));  // 参考数量
                qDto.put("XMDC011", mmrx_tPO.getString("MMRX003"));  // 计价数量
            }
//                    qDto.put("OEB24", 0);  // 已出货数量
            qDto.put("XMDC006", mmrx_tPO.getString("MMRX002"));  // 单位
            qDto.put("XMDC010", mmrx_tPO.getString("MMRX002"));  // 计价单位
            qDto.put("XMDC015", mmrx_tPO.getString("MMRX012"));   // 单价（使用的是本币单价）
            qDto.put("XMDC020", "1");   // 紧急程度（默认1：一般）
            qDto.put("XMDC012", "");  // 预交货日
            // 税率
            if (mmrx_tPO.getBigDecimal("GWEA006") == null || mmrx_tPO.getBigDecimal("GWEA006").equals(new BigDecimal(0.00))) {
                qDto.put("XMDC017", 0.16);
            } else {
                qDto.put("XMDC017", mmrx_tPO.getBigDecimal("GWEA006").divide(new BigDecimal(100), 4, RoundingMode.HALF_UP));//根据税种mmrx007抓税率
            }

            // 税前金额
            if (mmrx_tPO.getBigDecimal("TDI01") == null) {
                qDto.put("XMDC046", 0);//mmrx014-mmrx016
            } else {
                qDto.put("XMDC046", mmrx_tPO.getBigDecimal("TDI01").setScale(2, RoundingMode.HALF_UP));//gwcs039-gwcs041
            }
            // 含税金额
            if (mmrx_tPO.getBigDecimal("MMRX014") == null) {
                qDto.put("XMDC047", 0);
            } else {
                qDto.put("XMDC047", mmrx_tPO.getBigDecimal("MMRX014").setScale(2, RoundingMode.HALF_UP));
            }
            // 税额
            if (mmrx_tPO.getBigDecimal("MMRX015") == null) {
                qDto.put("XMDC048", "");
            } else {
                qDto.put("XMDC048", mmrx_tPO.getBigDecimal("MMRX015").setScale(2, RoundingMode.HALF_UP));
            }



//                    qDto.put("OEBLEGAL", mmrx_tPO.getString("MMRXPLANT"));  // 所属法人
//                    qDto.put("OEBPLANT", mmrx_tPO.getString("MMRXPLANT"));   // 所属营运中心
//                    qDto.put("OEB1006", 1);  // 折扣率
//                    qDto.put("OEB932", 0); // 订单包装数量
//                    qDto.put("OEB901", 0);  // 已交包装数量

            this.execInsert(qDto,"XMDC_T");

            MmrxT mmrxT = new MmrxT();
            mmrxT.setMMRX029(infoDto.getString("dd01"));
            mmrxT.setMMRXACTI("Z");
            UpdateWrapper<MmrxT> mmrxTUpdateWrapper = new UpdateWrapper<>();
            mmrxTUpdateWrapper.eq("MMRXDOCNO", mmrx_tPO.getString("MMRXDOCNO"));
            mmrxTUpdateWrapper.eq("MMRXSEQ", mmrx_tPO.getString("MMRXSEQ"));
            mmrxT.update(mmrxTUpdateWrapper);
        }
    }

    /**
     * 维修费用收入转ERP订单(gwei025) : 增加交期明细
     * @param
     * @return
     */
    private void insertXmddBy025(List<Dto> mmrx_tPOs,Dto infoDto) {
        int seq = 1;
        for (Dto mmrx_tPO : mmrx_tPOs) {
            //单身信息
            Dto qDto = Dtos.newDto();
            qDto.put("ERP_Link", infoDto.getString("ERP_Link"));
            //按法人组织抓取单号
            DecimalFormat mFormat = new DecimalFormat("0000");//确定格式，把1 转换为0001
            String mmrxseq = mFormat.format(mmrx_tPO.getBigDecimal("MMRXSEQ"));

            qDto.put("XMDDENT",infoDto.getString("ENT"));
            qDto.put("XMDDDOCNO", infoDto.getString("dd01"));
            qDto.put("XMDDSEQ", mmrxseq);
            qDto.put("XMDDSEQ1", seq);
            qDto.put("XMDDSEQ2", seq);
            seq++;
            qDto.put("XMDD001", mmrx_tPO.getString("MMRX001"));

            qDto.put("XMDD004", mmrx_tPO.getString("MMRX002"));   // 单位
            qDto.put("XMDD026", mmrx_tPO.getString("MMRX002"));   // 分批计价单位
            qDto.put("XMDD005", mmrx_tPO.getString("MMRX003"));   // 订单数量
            qDto.put("XMDD019", mmrx_tPO.getString("MMRX007"));    // 税别
            qDto.put("XMDD009", 1);    // 交期类型
            qDto.put("XMDD015", 0);    // 已销退数量
            qDto.put("XMDD016", 0);    // 销退换货量
            qDto.put("XMDD031", 0);    // 已转出通量
            qDto.put("XMDD011", " ");  // 预交货日
            qDto.put("XMDD226", " ");  // 经营方式
            qDto.put("XMDD217", 0);  // 库存数量（待出货数量）

            // 税率
            if (mmrx_tPO.getBigDecimal("GWEA006") == null || mmrx_tPO.getBigDecimal("GWEA006").equals(new BigDecimal(0.00))) {
                qDto.put("XMDD020", 0.16);
            } else {
                qDto.put("XMDD020", mmrx_tPO.getBigDecimal("GWEA006").divide(new BigDecimal(100), 4, RoundingMode.HALF_UP));//根据税种mmrx007抓税率
            }
//
            // 税前金额
            if (mmrx_tPO.getBigDecimal("TDI01") == null) {
                qDto.put("XMDD028", 0);//mmrx014-mmrx016
            } else {
                qDto.put("XMDD028", mmrx_tPO.getBigDecimal("TDI01").setScale(2, RoundingMode.HALF_UP));//gwcs039-gwcs041
            }
            // 含税金额
            if (mmrx_tPO.getBigDecimal("MMRX014") == null) {
                qDto.put("XMDD029", 0);
            } else {
                qDto.put("XMDD029", mmrx_tPO.getBigDecimal("MMRX014").setScale(2, RoundingMode.HALF_UP));
            }
            // 税额
            if (mmrx_tPO.getBigDecimal("MMRX015") == null) {
                qDto.put("XMDC048", "");
            } else {
                qDto.put("XMDC048", mmrx_tPO.getBigDecimal("MMRX015").setScale(2, RoundingMode.HALF_UP));
            }


            this.execInsert(qDto,"XMDD_T");

            MmrxT mmrxT = new MmrxT();
            mmrxT.setMMRX029(infoDto.getString("dd01"));
            mmrxT.setMMRXACTI("Z");
            UpdateWrapper<MmrxT> mmrxTUpdateWrapper = new UpdateWrapper<>();
            mmrxTUpdateWrapper.eq("MMRXDOCNO", mmrx_tPO.getString("MMRXDOCNO"));
            mmrxTUpdateWrapper.eq("MMRXSEQ", mmrx_tPO.getString("MMRXSEQ"));
            mmrxT.update(mmrxTUpdateWrapper);
        }
    }

    /**
     * 维修费用收入转ERP订单(gwei025) : 插入失败处理
     * @param
     * @return
     */
    private void handleExceptionBy025(Dto mmrx_tPO,JSONArray json) {
        JSONObject jo = new JSONObject();
        jo.put("ERPRESULT", "N");//同步结果  Y  N
        jo.put("GWAK001", mmrx_tPO.getString("MMRX018"));//客户编号
        jo.put("GWAKL003",  mmrx_tPO.getString("MMRX018_NAME"));//客户名称
        jo.put("MMRXDOCNO",  mmrx_tPO.getString("MMRXDOCNO"));//订单号
        json.add(jo);
    }

    private void updateMmrx(String docno) {
        MmrxT mmrxT = new MmrxT();
        mmrxT.setMMRX029("");
        mmrxT.setMMRXACTI("Y");
        UpdateWrapper<MmrxT> mmrxTUpdateWrapper = new UpdateWrapper<>();
        mmrxTUpdateWrapper.eq("MMRXDOCNO", docno);
        mmrxT.update(mmrxTUpdateWrapper);
    }

    /**
     * 查询订单（xmda_t) 来源单号是否存在
     */
    private Dto getXmda008(Dto inDto) {
        String docno = inDto.getString("XMDA008");
        String ERP_Link = inDto.getString("ERP_Link");
        String ent = inDto.getString("XMDAENT");
        String site = inDto.getString("XMDASITE");

        String query = String.format("SELECT XMDA008,XMDASTUS,XMDADOCNO FROM XMDA_T "
                +"WHERE XMDAENT = ''%s'' AND XMDASITE = ''%s'' AND  XMDA008 = ''%s'' AND XMDASTUS != ''X'' ",ent,site,docno);
        String sql = String.format("SELECT * FROM OPENQUERY(%s,'%s')",ERP_Link,query);
        inDto.put("sql",sql);
        return this.baseMapper.selectExecSql(inDto);
    }

    /**
     * 更新订单（xmda_t)状态
     */
    private int updateXmdaStatus(Dto inDto) {
        String docno = inDto.getString("XMDADOCNO");
        String ERP_Link = inDto.getString("ERP_Link");
        String ent = inDto.getString("XMDAENT");
        String site = inDto.getString("XMDASITE");
        String status = inDto.getString("XMDASTUS");

        String sql = String.format("UPDATE OPENQUERY(%s,'SELECT * FROM XMDA_T "
                + "WHERE XMDAENT = ''%s'' AND XMDASITE = ''%s'' AND XMDADOCNO = ''%s'' AND XMDASTUS = ''N'' ') "
                + "SET XMDASTUS = '%s' ",ERP_Link, ent,site,docno, status);
        inDto.put("sql",sql);
        return this.baseMapper.updateExecSql(inDto);
    }

    /**
     * 执行exec 插入sql
     * @param inDto
     * @param tableName
     * @return
     */
    private int execInsert(Dto inDto,String tableName) {
        String insertSql = generateInsertSql(inDto,tableName);
        inDto.put("sql",insertSql);
        return this.baseMapper.insertExecSql(inDto);
    }

    /**
     * insert sql 构建器
     * @param inDto
     * @param tableName 需要插入的表名
     * @return
     */
    private String generateInsertSql(Dto inDto,String tableName) {
        // 截取表名前缀，用于判断inDto中那些参数需要被添加到insert中去
        String tablePrefix = tableName.substring(0,tableName.length()-2);
        String ERP_Link = inDto.getString("ERP_Link");
        String openqueryStr = String.format("INSERT INTO OPENQUERY(%s,'SELECT * FROM %s WHERE 1=0')",ERP_Link,tableName);

        // 需要插入的列
        StringBuilder columnStr = new StringBuilder("(");
        // 与列对应的values
        StringBuilder valueStr = new StringBuilder("VALUES(");

        Iterator iterator = inDto.entrySet().iterator();
        // 遍历传入的inDto
        while(iterator.hasNext()) {
            Map.Entry entry = (Map.Entry)iterator.next();
            String key = (String) entry.getKey();
            Object value = entry.getValue();

            if(value == null || value.equals("")) continue;

            // 如果参数名前面包含表名前缀则认为可以插入
            if(key.startsWith(tablePrefix) ) {
                columnStr.append(key).append(",");
                String tmpValue = String.format("'%s'",value);
                valueStr.append(tmpValue).append(",");
            }
        }
        // 去掉最后一列后面的逗号
        columnStr.deleteCharAt(columnStr.length()-1);
        valueStr.deleteCharAt(valueStr.length()-1);

        columnStr.append(")");
        valueStr.append(")");
        return openqueryStr + columnStr.toString() + valueStr.toString();
    }

    /**
     * 审核订单变更单(gwai770)
     */
    public Dto checkGwai770(Dto inDto){
        Dto outDto = Dtos.newDto();
        outDto.put("code", 200);
        List<GwdfT> gwdfTList = this.gwdfTService.getGwdfData(inDto);
        List<Dto> change = new ArrayList();
        int count_1 = 0;
        int count_2 = 0;
        for (GwdfT gwdfT : gwdfTList) {
            Dto queryDto = Dtos.newDto();
            queryDto.put("XMDLSITE", gwdfT.getGWDFMLEGAL());
            queryDto.put("XMDLENT", inDto.getString("ENT"));
            inDto.put("MB001", gwdfT.getGWDFMLEGAL());
            queryDto.put("XMDL003", gwdfT.getGWDF003());//订单号
            queryDto.put("XMDL004", gwdfT.getGWDF004());//订单项序
            queryDto.put("ERP_Link", inDto.getString("ERP_Link"));
            queryDto.put("sqlName", "getXmdl018Sum");
            String sql = this.gwai770Sql(queryDto);
            queryDto.put("sql",sql);
            Dto sumXmdl018 = this.baseMapper.selectSql(queryDto);
            if (sumXmdl018 == null) {
                sumXmdl018 = Dtos.newDto();
                sumXmdl018.put("XMDL018_SUM", 0);
            }
            if (sumXmdl018.getBigDecimal("XMDL018_SUM").compareTo(gwdfT.getGWDF015()) == 0) {
                if (gwdfT.getGWDF015().compareTo(gwdfT.getGWDF014()) < 1) {
                    continue;
                } else {
                    count_2++;
                }
            } else {
                Dto changeDto = Dtos.newDto();
                changeDto.put("GWDF003", gwdfT.getGWDF003());
                changeDto.put("GWDF004", gwdfT.getGWDF004());
                changeDto.put("GWDF015", sumXmdl018.getBigDecimal("XMDL018_SUM"));
                change.add(changeDto);
                count_1++;
            }
        }
        if (count_1 > 0) {
            outDto.put("code", 300);
            outDto.put("change_list", change);
        } else if (count_2 > 0) {
            outDto.put("code", 400);
        } else {//修改分销订单及ERP订单数据
            for (GwdfT gwdfT : gwdfTList) {
                if (gwdfT.getGWDF004() == null || ("").equals(gwdfT.getGWDF004())) {
                    //查询ERP数据，获取该单号最大项次
                    Dto QDto = Dtos.newDto();
                    QDto.put("ERP_Link",inDto.getString("ERP_Link"));
                    QDto.put("XMDCSITE",gwdfT.getGWDFMLEGAL());
                    QDto.put("XMDCENT",inDto.getString("ENT"));
                    QDto.put("XMDCDOCNO",gwdfT.getGWDF003());
                    QDto.put("sqlName","getMaxXmdcseq");
                    String sql = this.gwai770Sql(QDto);
                    QDto.put("sql", sql);
                    Dto maxXmdcseq = this.baseMapper.selectSql(QDto);
                    Dto gwamQ = Dtos.newDto();
                    gwamQ.put("ENT", inDto.getString("ENT"));
                    gwamQ.put("LANG", inDto.getString("LANG"));
                    gwamQ.put("GWAM001", gwdfT.getGWDF011());
                    Dto gwam = this.gwdfTService.getGwam(gwamQ);
                    GwcsT gwcsTQ = this.gwdfTService.getMaxGwcsseq(gwdfT.getGWDF001());
                    try {
                        this.gwdfTService.addGwcs(gwcsTQ, gwdfT);
                        this.insertXmdcBy770(maxXmdcseq, gwdfT, gwam, gwcsTQ,inDto);
                    } catch (Exception e) {
                        BigDecimal eb003 = maxXmdcseq.getBigDecimal("XMDCSEQ_MAX").add(new BigDecimal(1));
                       /* DecimalFormat df = new DecimalFormat("0000");
                        String eb003 = df.format(OEB03);*/
                        Dto delXmdc = Dtos.newDto();
                        delXmdc.put("XMDCSITE", gwdfT.getGWDFMLEGAL());
                        delXmdc.put("XMDCENT", inDto.getString("ENT"));
                        delXmdc.put("XMDCDOCNO", gwdfT.getGWDF003());//订单号
                        delXmdc.put("XMDCSEQ", eb003);//订单项次
                        delXmdc.put("ERP_Link", inDto.getString("ERP_Link"));
                        this.gwdfTService.delGwcs(gwcsTQ);

                        delXmdc.put("sqlName", "deleteXmdc");
                        String delSql = this.gwai770Sql(delXmdc);
                        delXmdc.put("sql", delSql);
                        this.baseMapper.deleteExecSql(delXmdc);

                        delXmdc.put("sqlName", "updateXmda");
                        String xmdaSql = this.gwai770Sql(delXmdc);
                        delXmdc.put("sql", xmdaSql);
                        this.baseMapper.updateExecSql(delXmdc);
                        e.printStackTrace();
                        outDto.put("code", 500);
                        outDto.put("message", "订单变更单确认失败！" + e.getMessage());
                    }
                }
                //修改ERP数据
                Dto XMDC = Dtos.newDto();
                XMDC.put("ERP_Link", inDto.getString("ERP_Link"));
                XMDC.put("XMDCSITE", gwdfT.getGWDFMLEGAL());
                XMDC.put("XMDCENT", inDto.getString("ENT"));
                XMDC.put("XMDA071", gwdfT.getGWDF031());//备注
                XMDC.put("XMDC007", gwdfT.getGWDF014());//订单数量
                //XMDC.put("OEB09", gwdfT.getGWDF023());//仓库
                XMDC.put("XMDC015", gwdfT.getGWDF017());//价格
                XMDC.put("XMDC047", gwdfT.getGWDF026());//金额
                XMDC.put("XMDC046", gwdfT.getGWDF026().subtract(gwdfT.getGWDF029()));//税前金额
                XMDC.put("XMDC048", gwdfT.getGWDF029());//税额
                XMDC.put("XMDCDOCNO", gwdfT.getGWDF003());//订单号
                XMDC.put("XMDCSEQ", gwdfT.getGWDF004());//订单项次
                //XMDC.put("OEB1006", gwdfT.getGWDF036());//折扣率

                //更新分销订单数据
                GwcsT gwcsT = new GwcsT();
                //gwcsT.setGWCS050(gwdfT.getGWDF031());//备注
                //gwcsT.setGWCS117(gwdfT.getGWDF007());//返利类型
                gwcsT.setGWCS003(gwdfT.getGWDF014());//订单数量
                gwcsT.setGWCS113(gwdfT.getGWDF023());//仓库
                gwcsT.setGWCS004(gwdfT.getGWDF017());//价格
                gwcsT.setGWCS005(gwdfT.getGWDF026());//金额
                gwcsT.setGWCS040(gwdfT.getGWDF029());//税额
                gwcsT.setGWCS112(gwdfT.getGWDF021());//仓库类型
                gwcsT.setGWCS035(gwdfT.getGWDF036());//折扣
                gwcsT.setGWCSDOCNO(gwdfT.getGWDF001());//订单号
                gwcsT.setGWCSSEQ(gwdfT.getGWDF005());//订单项次
                gwcsT.setGWCSENT(gwdfT.getGWDFENT());

                GwcsT gwcsTNew = new GwcsT();
                gwcsTNew.setGWCS117(gwdfT.getGWDF007());//返利类型
                gwcsTNew.setGWCSDOCNO(gwdfT.getGWDF001());//订单号
                gwcsTNew.setGWCS050(gwdfT.getGWDF031());//备注
                gwcsTNew.setGWCSENT(gwdfT.getGWDFENT());

                //更新赠品
                GwcszT gwcszT = new GwcszT();
                gwcszT.setGWCSZENT(gwdfT.getGWDFENT());
                gwcszT.setGWCSZDOCNO(gwdfT.getGWDF001());
                gwcszT.setGWCSZSEQ(gwdfT.getGWDF004());//erp变更单项序
                gwcszT.setGWCSZ005(gwdfT.getGWDF014());//价格
                try {
                    this.gwdfTService.updateGWCS_GWCSZ(gwcsT, gwcszT, gwcsTNew);

                    XMDC.put("sqlName","updateXmdc");
                    String updateXmdc = this.gwai770Sql(XMDC);
                    XMDC.put("sql", updateXmdc);
                    this.baseMapper.updateExecSql(XMDC);

                    XMDC.put("sqlName","updateXmda");
                    String updateXmda = this.gwai770Sql(XMDC);
                    XMDC.put("sql", updateXmda);
                    this.baseMapper.updateExecSql(XMDC);
                } catch (Exception e) {
                    e.printStackTrace();
                    outDto.put("code", 500);
                    outDto.put("message", "订单变更单确认失败！" + e.getMessage());
                }

            }
            this.gwdfTService.updateGwdf(inDto);
        }
        return outDto;
    }

    public void insertXmdcBy770(Dto maxXmdcseq, GwdfT gwdfT, Dto gwam, GwcsT gwcs, Dto inDto) {
        BigDecimal XMDCSEQ = maxXmdcseq.getBigDecimal("XMDCSEQ_MAX").add(new BigDecimal(1));
        /*DecimalFormat df = new DecimalFormat("0000");
        String eb003 = df.format(OEB03);*/

        Dto xmdc = Dtos.newDto();
        xmdc.put("ERP_Link",inDto.getString("ERP_Link"));
        xmdc.put("XMDCSITE", inDto.getString("XMDCSITE"));//目标数据库
        xmdc.put("XMDCENT", gwdfT.getGWDFMLEGAL());//目标数据库

        xmdc.put("XMDCDOCNO", gwdfT.getGWDF003());
        xmdc.put("XMDCSEQ", XMDCSEQ);
        xmdc.put("XMDC001", gwdfT.getGWDF011());//取CRM中购物车的品号(需要判断是否在ERP中是否存在?）
        xmdc.put("XMDC002", "");//产品特征
        xmdc.put("XMDC003", "");//包装容器
        xmdc.put("XMDC004", "");//作业编号
        xmdc.put("XMDC005", "");//制进程
        xmdc.put("XMDC006", gwdfT.getGWDF012());//销售单位
        xmdc.put("XMDC007", gwdfT.getGWDF014());//销售数量
        xmdc.put("XMDC008", gwdfT.getGWDF012());//参考单位
        xmdc.put("XMDC009", gwdfT.getGWDF014());//参考数量
        xmdc.put("XMDC010", gwdfT.getGWDF012());//计价单位
        xmdc.put("XMDC011", gwdfT.getGWDF012());//计价数量
        xmdc.put("XMDC012", gwcs.getGWCS016());//约定交货日
        xmdc.put("XMDC013", "");//预定签收日
        xmdc.put("XMDC015", gwdfT.getGWDF016());//单价
        xmdc.put("XMDC016", gwcs.getGWCS032());//税别
        xmdc.put("XMDC017", gwdfT.getGWDF010());//税率
        xmdc.put("XMDC019", "");//子件特性
        xmdc.put("XMDC020", "");//急料
        xmdc.put("XMDC021", "");//保税
        xmdc.put("XMDC022", "");//部分交货
        xmdc.put("XMDCUNIT", "");//出货据点
        xmdc.put("XMDCUORGA", "");//收款据点
        xmdc.put("XMDC023", "");//收货客户
        xmdc.put("XMDC024", "");//多交期
        xmdc.put("XMDC025", "");//收货地址代码
        xmdc.put("XMDC026", "");//账款地址代码
        xmdc.put("XMDC027", "");//客户料号
        xmdc.put("XMDC028", "");//限定库位
        xmdc.put("XMDC029", "");//限定储位
        xmdc.put("XMDC030", "");//限定批号
        xmdc.put("XMDC031", "");//运输方式
        xmdc.put("XMDC032", "");//取货模式
        xmdc.put("XMDC033", "");//备品率
        xmdc.put("XMDC034", "");//可超交率
        xmdc.put("XMDC035", "");//价格核决
        xmdc.put("XMDC036", "");//专案编号
        xmdc.put("XMDC037", "");//WBS编号
        xmdc.put("XMDC038", "");//活动编号
        xmdc.put("XMDC039", "");//费用原因
        xmdc.put("XMDC040", "");//取价来源
        xmdc.put("XMDC041", "");//价格参考单号
        xmdc.put("XMDC042", "");//价格参考项次
        xmdc.put("XMDC043", "");//取出价格
        xmdc.put("XMDC044", "");//价差比
        xmdc.put("XMDC045", "N");//状态码
        xmdc.put("XMDC046", gwdfT.getGWDF026().subtract(gwdfT.getGWDF029()));//未税金额
        xmdc.put("XMDC047", gwdfT.getGWDF026());//含税金额
        xmdc.put("XMDC048", gwdfT.getGWDF029());//税额
        xmdc.put("XMDC049", "");//理由码
        xmdc.put("XMDC050", gwdfT.getGWDF031());//备注
        xmdc.put("XMDC051", "");//客户订单项次
        xmdc.put("XMDC052", "N");//检验否
        xmdc.put("XMDC053", "N");//结案理由码
        xmdc.put("XMDC054", "N");//BOM有效日期
        xmdc.put("XMDC055", gwcs.getGWCSDOCNO());//来源单号
        xmdc.put("XMDC056", gwcs.getGWCSSEQ().add(new BigDecimal(1)));//来源项次
        xmdc.put("XMDC057", "");//库存管理特征
        xmdc.put("XMDC058", "");//还量数量
        xmdc.put("XMDC059", "");//还量参考数量
        xmdc.put("XMDC060", "");//还价数量
        xmdc.put("XMDC061", "");//还价参考数量

        String sql = this.generateInsertSql(xmdc, "XMDC_T");
        xmdc.put("sql",sql);
        this.baseMapper.insertExecSql(xmdc);
        //this.baseMapper.updateCOPTCSum(COPTD);
    }

    public String gwai770Sql(Dto inDto){
        String sql = "";
        if("getXmdl018Sum".equals(inDto.getString("sqlName"))){
            String query = "SELECT XMDLENT,XMDLSITE,XMDL003,XMDL004,SUM(XMDL018) AS XMDL018_SUM FROM XMDL_T "+
                    "WHERE XMDLENT=''"+ inDto.getString("XMDLENT")
                    +"'' AND XMDLSITE=''"+ inDto.getString("XMDLSITE")
                    +"'' AND XMDL003=''"+ inDto.getString("XMDL003")+
                    "'' AND XMDL004=''"+inDto.getString("XMDL004")+"'' "+
                    "GROUP BY XMDLENT,XMDLSITE,XMDL003,XMDL004";
                    /*"ORDER BY XMDLENT,XMDLSITE,XMDL003,XMDL004";*/
            sql = "SELECT * FROM OPENQUERY(" + inDto.getString("ERP_Link") + ",'" + query + "')";
        }else if("getMaxXmdcseq".equals(inDto.getString("sqlName"))){
            String query = "SELECT MAX(XMDCSEQ) AS XMDCSEQ_MAX FROM XMDC_T "
                    +"WHERE XMDCENT=''"+ inDto.getString("XMDCENT")
                    +"'' AND XMDCSITE=''"+ inDto.getString("XMDCSITE")
                    +"'' AND XMDCDOCNO=''"+ inDto.getString("XMDCDOCNO")+"''";
            sql = "SELECT * FROM OPENQUERY(" + inDto.getString("ERP_Link") + ",'" + query + "')";
        }else if("deleteXmdc".equals(inDto.getString("sqlName"))){
            String del = "SELECT * FROM XMDC_T "
                    + "WHERE XMDCENT=''"+ inDto.getString("XMDCENT")
                    + "'' AND XMDCSITE=''" + inDto.getString("XMDCSITE")
                    + "'' AND XMDCDOCNO=''" + inDto.getString("XMDCDOCNO")
                    + "'' AND XMDCSEQ=''" + inDto.getString("XMDCSEQ") + "''";
            sql = "DELETE FROM OPENQUERY("+ inDto.getString("ERP_Link") + ",'" + del + "')";
        }else if("updateXmdc".equals(inDto.getString("sqlName"))){
            String update = "SELECT * FROM XMDC_T "
                    + "WHERE XMDCENT=''"+ inDto.getString("XMDCENT")
                    + "'' AND XMDCSITE=''" + inDto.getString("XMDCSITE")
                    + "'' AND XMDCDOCNO=''" + inDto.getString("XMDCDOCNO")
                    + "'' AND XMDCSEQ=''" + inDto.getString("XMDCSEQ") + "''";
            sql = "UPDAE OPENQUERY("+ inDto.getString("ERP_Link") + ",'" + update + "')"
                    +"SET XMDC007=''" + inDto.getString("XMDC007")
                    + "'',XMDC015=''" + inDto.getString("XMDC015")
                    + "'',XMDC047=''" + inDto.getString("XMDC047")
                    + "'',XMDC046=''" + inDto.getString("XMDC046")
                    + "'',XMDC048=''" + inDto.getString("XMDC048")+"''";
        }else if("updateXmda".equals(inDto.getString("sqlName"))){
            String update = "SELECT * FROM XMDA_T "
                    + "WHERE XMDAENT=''"+ inDto.getString("XMDCENT")
                    + "'' AND XMDASITE=''" + inDto.getString("XMDCSITE")
                    + "'' AND XMDADOCNO=''" + inDto.getString("XMDCDOCNO")
                    + "'' AND XMDASEQ=''" + inDto.getString("XMDCSEQ") + "''";
            String xmda041Sum = "SELECT SUM(XMDC046) FROM XMDC_T "
                    + "WHERE XMDCENT=''"+ inDto.getString("XMDCENT")
                    + "'' AND XMDCSITE=''" + inDto.getString("XMDCSITE")
                    + "'' AND XMDCDOCNO=''" + inDto.getString("XMDCDOCNO") + "''";
            String xmda042Sum = "SELECT SUM(XMDC047) FROM XMDC_T "
                    + "WHERE XMDCENT=''"+ inDto.getString("XMDCENT")
                    + "'' AND XMDCSITE=''" + inDto.getString("XMDCSITE")
                    + "'' AND XMDCDOCNO=''" + inDto.getString("XMDCDOCNO") + "''";
            String xmda043Sum = "SELECT SUM(XMDC048) FROM XMDC_T "
                    + "WHERE XMDCENT=''"+ inDto.getString("XMDCENT")
                    + "'' AND XMDCSITE=''" + inDto.getString("XMDCSITE")
                    + "'' AND XMDCDOCNO=''" + inDto.getString("XMDCDOCNO") + "''";
            sql = "UPDATE OPENQUERY("+ inDto.getString("ERP_Link") + ",'" + update + "')"
                    + "SET XMDA041=(SELECT * FROM OPENQUERY("+ inDto.getString("ERP_Link")+",'" + xmda041Sum + "'),"
                    + "XMDA042=(SELECT * FROM OPENQUERY("+ inDto.getString("ERP_Link") + ",'" + xmda042Sum + "'),"
                    + "XMDA043=(SELECT * FROM OPENQUERY("+ inDto.getString("ERP_Link") + ",'" + xmda043Sum + "')";
            if(inDto.getString("XMDA017") != null){
                sql = ",XMDA071=''"+ inDto.getString("XMDA017") +"''";
            }
        }
        return sql;
    }

    public JSONArray insertErpGwak(Dto inDto) {
        String[] gwak001s = inDto.getString("gwak001_list").split(",");
        String[] MB001s = inDto.getString("mb001_list").split(",");
        ShiroUser shiroUser = ShiroKit.getUser();
        // 数据库主机
        String ERP_Link = inDto.getString("ERP_Link");
        JSONArray json = new JSONArray();
        for (String gwak001 : gwak001s) {
            //一条客户资料数据
            Dto gwakDto = Dtos.newDto();
            gwakDto.put("ent", shiroUser.getDBC());
            gwakDto.put("lang", LangUtils.getLang(shiroUser.getLANG()));
            gwakDto.put("gwak001", gwak001);
            Dto info = gwakTService.getGwakData(gwakDto);
            for (String MB001 : MB001s) {
                //是否写入成功
                String result = "N";
                if (MB001 != null) {
                    //判断客户编号在ERP中是否存在 不存在就新增一笔客户数据
                    Dto inDto2 = Dtos.newDto();
                    inDto2.put("PMAA001", gwak001);
                    inDto2.put("ERP_Link", ERP_Link);
                    inDto2.put("PMAAENT", shiroUser.getDBC());
                    inDto2.put("sql", this.generateSql710(inDto2, "selectByGwak001"));
                    Dto outDto2 = this.baseMapper.selectExecSql(inDto2);
                    int count = 0;
                    //  客户不存在，将客户资料同步到ERP
                    if (outDto2 == null || outDto2.getString("PMAA001").isEmpty()) {
                        try {
                            count = this.gwakData(inDto2.getString("PMAA001"), ERP_Link, "add");
                        } catch (Exception e) {
                            JSONObject jo = new JSONObject();
                            jo.put("SYNCRESULT", result);//同步结果  Y  N syncresult
                            jo.put("GWAK001", info.getString("GWAK001"));//客户编号
                            jo.put("GWAKL003", info.getString("GWAKL003"));//客户名称
                            jo.put("REMARK", e.getMessage());
                            if (MB001 != null) {
                                jo.put("MB002", MB001);//erp公司
                            } else {
                                jo.put("MB002", "");//erp公司
                            }
                            json.add(jo);
                            continue;
                        }
                    } else {
                        try {
                            count = this.gwakData(inDto2.getString("PMAA001"), ERP_Link, "update");
                        } catch (Exception e) {
                            JSONObject jo = new JSONObject();
                            jo.put("SYNCRESULT", result);//同步结果  Y  N syncresult
                            jo.put("GWAK001", info.getString("GWAK001"));//客户编号
                            jo.put("GWAKL003", info.getString("GWAKL003"));//客户名称
                            jo.put("REMARK", e.getMessage());
                            if (MB001 != null) {
                                jo.put("MB002", MB001);//erp公司
                            } else {
                                jo.put("MB002", "");//erp公司
                            }
                            json.add(jo);
                            continue;
                        }
                    }
                    if (count > 0) {
                        result = "Y";
                    }
                }
                JSONObject jo = new JSONObject();
                jo.put("SYNCRESULT", result);//同步结果  Y  N syncresult
                jo.put("GWAK001", info.getString("GWAK001"));//客户编号
                jo.put("GWAKL003", info.getString("GWAKL003"));//客户名称
                jo.put("REMARK", "");
                if (MB001 != null) {
                    jo.put("MB002", MB001);//erp公司
                } else {
                    jo.put("MB002", "");//erp公司
                }
                json.add(jo);
            }
        }
        return json;
    }

    public int gwakData(String gwak001, String ERP_Link,String type){
        ShiroUser shiroUser = ShiroKit.getUser();

        //获取gwak001对应的客户资料数据
        Dto qDto = Dtos.newDto();
        qDto.put("ent", shiroUser.getDBC());
        qDto.put("gwak001", gwak001);
        Dto info = this.gwakTService.getGwakData(qDto);

        //获取目标数据库
        Dto outDto = Dtos.newDto();
        outDto.put("ERP_Link", ERP_Link);
        outDto.put("PMAAENT", shiroUser.getDBC());
        outDto.put("PMAA001", info.getString("GWAK001"));
        outDto.put("PMAA016", info.getString("GWAK050"));//负责人
        if (info.getString("GWAK051").equals(null)) {//资本额
            outDto.put("PMAA018", "");
        } else {
            outDto.put("PMAA018", info.getBigDecimal("GWAK051"));
        }
        if (info.getString("GWAK052").equals(null)) {//年营收
            outDto.put("PMAA021", "");
        } else {
            outDto.put("PMAA021", info.getBigDecimal("GWAK052"));
        }
        outDto.put("PMAA011", info.getString("GWAK008"));//交易币别
        outDto.put("PMAA055", 0);   // 信用额度
        outDto.put("PMAA056", 0);   // 信用额度容许超出比率
        outDto.put("PMAA206", "2"); // 结算方式


        Dto lDto= Dtos.newDto();
        lDto.put("ERP_Link", ERP_Link);
        lDto.put("PMAALENT", shiroUser.getDBC());
        lDto.put("PMAAL001",info.getString("GWAK001"));
        lDto.put("PMAAL002",LangUtils.getLang(shiroUser.getLANG()));
        lDto.put("PMAAL003",info.getString("GWAKL004"));
        lDto.put("PMAAL004",info.getString("GWAKL003"));
        lDto.put("PMAAL005"," ");
        int i = 0;
        //将客户资料插入指定ERP数据库
        if("add".equals(type)) {
            i = this.execInsert(outDto, "PMAA_T");
            i = this.execInsert(lDto, "PMAAL_T");
        }else {
            String sqlStr = "SELECT * FROM PMAA_T WHERE PMAAENT=''"
                    + shiroUser.getDBC() +"'' AND PMAA001=''"+ gwak001 +"''";
            outDto.put("sqlStr",sqlStr);
            String sqlStrPmaal = "SELECT * FROM PMAAL_T WHERE PMAALENT=''"
                    + shiroUser.getDBC() +"'' AND PMAAL001=''"+ gwak001 +"''";
            lDto.put("sqlStr",sqlStrPmaal);
            i = this.baseMapper.updatePmaa(outDto);
            i = this.baseMapper.updatePmaal(lDto);
        }
        return i;
    }

    public Dto getXmdk001(Dto inDto){
        Dto outDto = Dtos.newDto();
        String query = "SELECT XMDAUA001, XMDK001, XMDCUA005, XMDCUA002, ROW_NUMBER () OVER ( PARTITION BY XMDAUA001, XMDCUA005, XMDCUA002 ORDER BY XMDK001 DESC ) A "+
                "FROM XMDC_T "
                +"LEFT JOIN XMDD_T ON XMDDENT=XMDCENT AND XMDDSITE=XMDCSITE AND XMDDDOCNO=XMDCDOCNO AND XMDDSEQ=XMDCSEQ "
                +"LEFT JOIN XMDA_T ON XMDAENT=XMDCENT AND XMDASITE=XMDCSITE AND XMDADOCNO=XMDCDOCNO "
                +"LEFT JOIN XMDL_T ON XMDLENT=XMDDENT AND XMDLSITE=XMDDSITE AND XMDL003=XMDDDOCNO AND XMDL004=XMDDSEQ AND XMDL005=XMDDSEQ1 AND XMDL006=XMDDSEQ2 "
                +"LEFT JOIN XMDK_T ON XMDKENT=XMDLENT AND XMDKSITE=XMDLSITE AND XMDKDOCNO=XMDLDOCNO "
                +"WHERE XMDKSTUS=''S'' AND XMDAUA001=''"+ inDto.getString("XMDAUA001") +"'' AND XMDCUA005=''"+ inDto.getString("XMDCUA005")
                + "'' AND XMDCENT=''" + inDto.getString("ENT") + "''";
        String sql = "SELECT TO_CHAR(XMDK001,'yyyy-MM-dd') XMDK001 FROM OPENQUERY(" + inDto.getString("ERP_Link") + ",'" + query + "') WHERE A=1";
        outDto = this.baseMapper.selectExecSql(inDto);
        inDto.put("sql",sql);
        return outDto;
    }

    public Dto getXmdd014(Dto inDto){
        Dto outDto = Dtos.newDto();
        String query = "SELECT SUM(XMDD014) XMDD014 "+
                "FROM XMDC_T "
                +"LEFT JOIN XMDD_T ON XMDDENT=XMDCENT AND XMDDSITE=XMDCSITE AND XMDDDOCNO=XMDCDOCNO AND XMDDSEQ=XMDCSEQ "
                +"LEFT JOIN XMDA_T ON XMDAENT=XMDCENT AND XMDASITE=XMDCSITE AND XMDADOCNO=XMDCDOCNO "
                +"WHERE XMDAUD001=''"+ inDto.getString("XMDAUA001") +"'' AND XMDCUD005=''"+ inDto.getString("XMDCUA005")
                + "'' AND XMDCENT=''" + inDto.getString("ENT") + "'' "
                +"GROUP BY XMDAUD001,XMDCUD005,XMDCUD002";
                /*+"WHERE XMDAUA001=''"+ inDto.getString("XMDAUA001") +"'' AND XMDCUA005=''"+ inDto.getString("XMDCUA005")
                + "'' AND XMDCENT=''" + inDto.getString("ENT") + "'' "
                +"GROUP BY XMDAUA001,XMDCUA005,XMDCUA002";*/
        String sql = "SELECT * FROM OPENQUERY(" + inDto.getString("ERP_Link") + ",'" + query + "')";
        inDto.put("sql",sql);
        outDto = this.baseMapper.selectExecSql(inDto);
        return outDto;
    }

    public Dto getGwcq003Data(Dto inDto) {
        String query = "SELECT A.*,(A.Amount_Received - A.Actual_Amount_Received) Amount_NotReceived FROM ("
                + "SELECT DISTINCT "
                + " (SELECT SUM(XRCC108) FROM XRCC_T WHERE XRCCDOCNO=XRCADOCNO) Amount_Received,"
                + " (SELECT SUM(XRCE109) FROM XRCE_T WHERE XRCE003=XRCADOCNO) Actual_Amount_Received ,"
                + " (SELECT MAX(XRDADOCDT) FROM XRDA_T,XRCE_T WHERE XRDADOCNO=XRCEDOCNO AND XRCE003=XRCADOCNO) Actual_payment_date"
                + " FROM XMDA_T"
                + " LEFT JOIN XMDB_T ON XMDBDOCNO = XMDADOCNO "
                + " LEFT JOIN XRCA_T ON XRCADOCNO = XMDB007 "
                + " LEFT JOIN XRCC_T ON XRCADOCNO = XRCCDOCNO "
                + " WHERE XMDADOCNO =  ''"+ inDto.getString("GWCA054") +"'' "
                +") A";
        String sql = "SELECT * FROM OPENQUERY(" + inDto.getString("ERP_Link") + ",'" + query + "')";
        inDto.put("sql",sql);
        return this.baseMapper.selectExecSql(inDto);
    }
}
